受欢迎的博客标签

he 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";
        }

后台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