.net core 使用api client 调用api

Create Some APIs 

Here I use ASP.NET Core WebAPI to creat some RESTful APIs.

[Route("api/[controller]")]  
public class PersonsController : Controller  
{  
    // GET: api/persons  
    [HttpGet]  
    public IEnumerable Get()  
    {  
        return new List  
        {  
            new Person{Id = 1 , Name = "catcher wong"},  
            new Person{Id = 2 , Name = "james"}  
        };  
    }  
  
    // GET api/persons/5  
    [HttpGet("{id}")]  
    public Person Get(int id)  
    {  
        return new Person { Id = id, Name = "name" };  
    }  
  
    // POST api/persons  
    [HttpPost]  
    public Person Post([FromBody]Person person)  
    {  
        if (person == nullreturn new Person();  
  
        return new Person { Id = person.Id, Name = person.Name };  
    }  
  
    // PUT api/persons/  
    [HttpPut]  
    public string Put([FromBody]int id)  
    {  
        return $"put {id}";  
    }  
  
    // DELETE api/persons/5  
    [HttpDelete("{id}")]  
    public string Delete(int id)  
    {  
        return $"del {id}";  
    }  
}  
Interface Declaration

Create an interface named IPersonApiClient which inherit from IHttpApiClient.

public interface IPersonApiClient : IHttpApiClient { }  
Add some methods that need to call APIs.

Every method must have a HTTP attribute that provides the request method and relative URL. The return type should be ITask.

[HttpGet("/api/persons")]    
ITask> GetPersonsAsync();    
A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by { and }.

[HttpGet("/api/persons/{id}")]  
ITask GetPersonAsync(int id);  
When our requst parameters should in request body, we can use some attributes to specify the content, such as JsonContent, FormContent .etc.

[HttpPost("/api/persons")]  
ITask AddPersonAsync([JsonContent]Person person);   
The following code demonstrates the basic usage.

public interface IPersonApiClient : IHttpApiClient  
{  
    [HttpGet("/api/persons")]  
    ITask> GetPersonsAsync();  
  
    [HttpGet("/api/persons/{id}")]  
    ITask GetPersonAsync(int id);  
  
    [HttpPost("/api/persons")]  
    ITask AddPersonAsync([JsonContent]Person person);  
  
    [HttpPut("/api/persons")]  
    ITask EditPersonAsync([JsonContent]int id);  
  
    [HttpDelete("/api/persons/{id}")]  
    ITask DeletePersonAsync(int id);  
}  
The next step is how to retrieve the response of the request.

Retrieving Response

We should create a client first. After creating , what we need to do is call the methods we declared in the interface.

//specify the config  
var config = new HttpApiConfig  
{                  
    HttpHost = new Uri("http://localhost:9999"),  
};  
  
var client = HttpApiClient.Create(config);  
  
var persons = await client.GetPersonsAsync();  
  
Console.WriteLine("GetPersonsAsync result:");  
foreach (var item in persons)  
{  
    Console.WriteLine($"{item.Id}-{item.Name}");  
}  
  
var person = await client.GetPersonAsync(1000);  
Console.WriteLine("GetPersonAsync result:");  
Console.WriteLine($"{person.Id}-{person.Name}");  
  
  
var newPerson = new Person { Id = 999, Name = "999" };  
var postResult = await client.AddPersonAsync(newPerson);  
Console.WriteLine("AddPersonAsync result:");  
Console.WriteLine($"{postResult.Id}-{postResult.Name}");  
  
  
var editResult = await client.EditPersonAsync(1);  
Console.WriteLine("EditPersonAsync result:");  
Console.WriteLine($"{editResult}");  
  
var delResult = await client.DeletePersonAsync(1);  
Console.WriteLine("DeletePersonAsync result:");  
Console.WriteLine($"{delResult}");  
 

posted on 2022-04-24 17:38 青蛙學堂 阅读(371) 评论(0)  编辑 收藏 引用 所属分类: c#

只有注册用户登录后才能发表评论。
<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿(8)

随笔分类

随笔档案

收藏夹

青蛙学堂

最新评论

阅读排行榜

评论排行榜