在.net core中,使用WebApiClient去調用restful Api的接口

原文鏈接:https://www.c-sharpcorner.com/article/using-webapiclient-to-call-rest-apis-in-net-core/

Create Some APIs 

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

  1. [Route("api/[controller]")]  
  2. public class PersonsController : Controller  
  3. {  
  4.     // GET: api/persons  
  5.     [HttpGet]  
  6.     public IEnumerable<Person> Get()  
  7.     {  
  8.         return new List<Person>  
  9.         {  
  10.             new Person{Id = 1 , Name = "catcher wong"},  
  11.             new Person{Id = 2 , Name = "james"}  
  12.         };  
  13.     }  
  14.   
  15.     // GET api/persons/5  
  16.     [HttpGet("{id}")]  
  17.     public Person Get(int id)  
  18.     {  
  19.         return new Person { Id = id, Name = "name" };  
  20.     }  
  21.   
  22.     // POST api/persons  
  23.     [HttpPost]  
  24.     public Person Post([FromBody]Person person)  
  25.     {  
  26.         if (person == null) return new Person();  
  27.   
  28.         return new Person { Id = person.Id, Name = person.Name };  
  29.     }  
  30.   
  31.     // PUT api/persons/  
  32.     [HttpPut]  
  33.     public string Put([FromBody]int id)  
  34.     {  
  35.         return $"put {id}";  
  36.     }  
  37.   
  38.     // DELETE api/persons/5  
  39.     [HttpDelete("{id}")]  
  40.     public string Delete(int id)  
  41.     {  
  42.         return $"del {id}";  
  43.     }  
  44. }  

Interface Declaration

Create an interface named IPersonApiClient which inherit from IHttpApiClient.

  1. 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<T>.

  1. [HttpGet("/api/persons")]    
  2. ITask<List<Person>> 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 }.

  1. [HttpGet("/api/persons/{id}")]  
  2. ITask<Person> GetPersonAsync(int id);  

When our requst parameters should in request body, we can use some attributes to specify the content, such as JsonContentFormContent .etc.

  1. [HttpPost("/api/persons")]  
  2. ITask<Person> AddPersonAsync([JsonContent]Person person);   

The following code demonstrates the basic usage.

  1. public interface IPersonApiClient : IHttpApiClient  
  2. {  
  3.     [HttpGet("/api/persons")]  
  4.     ITask<List<Person>> GetPersonsAsync();  
  5.   
  6.     [HttpGet("/api/persons/{id}")]  
  7.     ITask<Person> GetPersonAsync(int id);  
  8.   
  9.     [HttpPost("/api/persons")]  
  10.     ITask<Person> AddPersonAsync([JsonContent]Person person);  
  11.   
  12.     [HttpPut("/api/persons")]  
  13.     ITask<string> EditPersonAsync([JsonContent]int id);  
  14.   
  15.     [HttpDelete("/api/persons/{id}")]  
  16.     ITask<string> DeletePersonAsync(int id);  
  17. }  

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.

  1. //specify the config  
  2. var config = new HttpApiConfig  
  3. {                  
  4.     HttpHost = new Uri("http://localhost:9999"),  
  5. };  
  6.   
  7. var client = HttpApiClient.Create<IPersonApiClient>(config);  
  8.   
  9. var persons = await client.GetPersonsAsync();  
  10.   
  11. Console.WriteLine("GetPersonsAsync result:");  
  12. foreach (var item in persons)  
  13. {  
  14.     Console.WriteLine($"{item.Id}-{item.Name}");  
  15. }  
  16.   
  17. var person = await client.GetPersonAsync(1000);  
  18. Console.WriteLine("GetPersonAsync result:");  
  19. Console.WriteLine($"{person.Id}-{person.Name}");  
  20.   
  21.   
  22. var newPerson = new Person { Id = 999, Name = "999" };  
  23. var postResult = await client.AddPersonAsync(newPerson);  
  24. Console.WriteLine("AddPersonAsync result:");  
  25. Console.WriteLine($"{postResult.Id}-{postResult.Name}");  
  26.   
  27.   
  28. var editResult = await client.EditPersonAsync(1);  
  29. Console.WriteLine("EditPersonAsync result:");  
  30. Console.WriteLine($"{editResult}");  
  31.   
  32. var delResult = await client.DeletePersonAsync(1);  
  33. Console.WriteLine("DeletePersonAsync result:");  
  34. Console.WriteLine($"{delResult}");  

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章