如何从web api调用和读取响应

本文关键字:读取 响应 调用 api web | 更新日期: 2023-09-27 17:59:57

我是web api的新手。很抱歉问了一个非常基本的问题。假设这是我的webapi类结构

public class Person
{
    string FirstName;
    string LastName;
    public Person(string fn, string ln)
    {
        FirstName = fn;
        LastName = ln;
    }
}
public class Team
{
    string TeamName;
    Person TeamLeader;
    List<Person> TeamMembers;
    public Team(string name, Person lead, List<Person> members)
    {
        TeamName = name;
        TeamLeader = lead;
        TeamMembers = members;
    }
}
public class Response
{
    int ResponseCode;
    string ResponseMessage;
    object ResponsePayload;
    public Response(int code, string message, object payload)
    {
        ResponseCode = code;
        ResponseMessage = message;
        ResponsePayload = payload;
    }
}
public class PersonController : ApiController
{
    public Response Get()
    {
        Person tom = new Person("Tom", "Cruise");
        Response response = new Response(1, "It works!", tom);
        return response;
    }
}
public class TeamController : ApiController
{
    public Response Get()
    {
        Person tom = new Person("Tom", "Cruise");
        Person cindy = new Person("Cindy", "Cullen");
        Person jason = new Person("Jason","Lien");
        Team awesome = new Team("Awesome", jason, new List<Person>(){tom,cindy});
        Response response = new Response(1, "It works!", awesome);
        return response;
    }
}

现在告诉我如何从c#winform应用程序调用PersonController and TeamController Get函数,并在一段时间内将数据传递给webapi函数。

我是webapi的新手,我需要开发一个webapi,它将在单独的pc中运行,并且该webapi将由几个winform客户端使用。

winform客户端将个人和团队数据发送到web api,web api将数据保存到数据库中,并在某个时间再次从web api获取数据。我正在寻找一个例子,告诉我如何编写代码,在winform客户端和webapi之间创建交互。

当我们将数据从winform客户端发送到webapi时,我是否需要准备json字符串并将其发送到webAPI,或者它将在后台自动完成?

需要小钻头引导线。感谢

如何从web api调用和读取响应

关于如何从非mvc应用程序中使用WebApi,有一个很好的教程:http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

查看Microsoft.AspNet.WebApi.Client包(https://www.nuget.org/packages/microsoft.aspnet.webapi.client/),这有助于内容协商和JSON编写/解析。