受欢迎的博客标签

ASP.Net Core Web API Series: call ASP.NET Core Web API Using HttpClient

Published

There are many  frameworks out there that you could use for free such as:

1.HttpClient
2.System.Net.Http.Json (.Net core 3.x and later)
3.Microsoft.AspNetCore.Blazor.HttpClient

 

1.HttpClient

the best and most straightforward way to consume RestAPI is by using the HttpClient class.

In order to Consume RestAPI using HttpClient, we can use various methods like

CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
PostAsync
PutAsync
SendAsyn

HTTP POST request

post请求有3种方式,由请求头中的content-type决定,属于哪一种post请求

application/x-www-form-urlencoded: 普通http请求方式,参数是普通的url参数拼接
application/json: JSON请求方式,参数是json格式
multipart/form-data: 文件上传

 

Send a valid HTTP POST request to the web API:

curl -i -k \
    -H "Content-Type: application/json" \
    -d "{\"name\":\"Plush Squirrel\",\"price\":12.99}" \
    https://localhost:5001/products

In the preceding command:

-i displays the HTTP response headers.
-d implies an HTTP POST operation and defines the request body.
-H indicates that the request body is in JSON format. The header's value overrides the default content type of application/x-www-form-urlencoded.

 

 public static async Task<string> InsertQueuedEmail(QueuedEmailModel queuedEmailMode)
        {
          

            HttpClient httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri("http://localhost:6063/");
            httpClient.DefaultRequestHeaders.Accept.Clear();

            //step 1:明确和web API服务端的数据交换格式为json格式 Add an Accept header for JSON format. 为JSON格式添加一个Accept报头
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            httpClient.DefaultRequestHeaders.Add("User-Agent", ".NET Foundation Repository Reporter");


            string uri = "";

            uri = "http://localhost:5000/api/QueuedEmail";

            //step 2:将序列化后的数据转换为httpClient.PostAsync提交所需要的HttpContent类型
            var json = JsonConvert.SerializeObject(queuedEmailMode);

            //step 3:将序列化的数据转换为HttpContent类型,同时告诉后台wep API 此数据格式为json,设置 content_Type 为application/json,即:Content-Type: application/json
            HttpContent content = new StringContent(json, System.Text.Encoding.UTF8,"application/json");
            


            string responseBody = "";
            HttpResponseMessage response=null;

            try
            {
                 response = await httpClient.PostAsync(uri, content);

               
              
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Success");
                }


              

                // ... 
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine(e.Message);

               
            }
             responseBody = await response.Content.ReadAsStringAsync();
           

            return "ok";
        }

 

 private async static void Process()
        {
            //获取当前联系人列表
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            IEnumerable<Contact> contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            Console.WriteLine("当前联系人列表:");
            ListContacts(contacts);

            //添加新的联系人
            Contact contact = new Contact { Name = "王五", PhoneNo = "0512-34567890", EmailAddress = "[email protected]" };
            await httpClient.PostAsJsonAsync<Contact>("http://localhost/selfhost/api/contacts", contact);
            Console.WriteLine("添加新联系人“王五”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            ListContacts(contacts);

            //修改现有的某个联系人
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts/001");
            contact = (await response.Content.ReadAsAsync<IEnumerable<Contact>>()).First();
            contact.Name = "赵六";
            contact.EmailAddress = "[email protected]";
            await httpClient.PutAsJsonAsync<Contact>("http://localhost/selfhost/api/contacts/001", contact);
            Console.WriteLine("修改联系人“001”信息:");
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            ListContacts(contacts);

            //删除现有的某个联系人
            await httpClient.DeleteAsync("http://localhost/selfhost/api/contacts/002");
            Console.WriteLine("删除联系人“002”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            ListContacts(contacts);
        }

后台api

namespace Nop.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class QueuedEmailController : Controller
    {
        #region Fields
        private readonly IQueuedEmailService _queuedEmailService;
        private readonly ILogger _logger;

        #endregion

        #region Constructors

        public QueuedEmailController(
            IQueuedEmailService queuedEmailService,
            ILogger<QueuedEmailController> logger


            )
        {
            _queuedEmailService = queuedEmailService;
            this._logger = logger;



        }

        #endregion

        // GET: api/<controller>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>  Create
        [HttpPost] 
        public void Post([FromBody]QueuedEmailModel model)
        {
            //if (queuedEmail == null
            var queuedEmail = new QueuedEmail();
            queuedEmail.Subject = model.Subject;
            queuedEmail.Body = model.Body;
            queuedEmail.From = model.From;
            queuedEmail.To = model.To;
            queuedEmail.CreatedOnUtc = DateTime.UtcNow;


            _queuedEmailService.InsertQueuedEmail(queuedEmail);
        }

 

HTTP PUT Request

Same as POST, HttpClient also supports all three methods: PutAsJsonAsync, PutAsXmlAsync and PutAsync.

 

Consume ASP.NET Core Web API Using HttpClient

 

2.Microsoft.AspNetCore.Blazor.HttpClient

Could not find GetJsonAsync in HttpClient class?

<PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.0.0-preview8.19405.7" PrivateAssets="all" />
response = await Http.GetJsonAsync<T>(Uri);

3.System.Net.Http.Json (.Net core 3.x and later)

get

todoItems = await Http.GetFromJsonAsync<TodoItem[]>("api/TodoItems");

post

 var addItem = new TodoItem { Name = newItemName, IsComplete = false };
       
//Calls to PostAsJsonAsync return an HttpResponseMessage
HttpResponseMessage response= await Http.PostAsJsonAsync("api/TodoItems", addItem);

//To deserialize the JSON content from the response message, use the ReadFromJsonAsync<T> extension method
var content = response.Content.ReadFromJsonAsync<WeatherForecast>();

https://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-5.0