1.第一步,在启动文件添加
builder.Services.AddHttpClient();
实体类:
public class SearchReq { public string Name { get; set; } public string Description { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } }
using Microsoft.AspNetCore.Mvc; using System.Text; using System.Text.Json; using WebApplication8._6.Model; using static System.Net.Mime.MediaTypeNames; namespace WebApplication8._6.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class ValuesController : ControllerBase { private readonly IHttpClientFactory _httpClientFactory; public ValuesController(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } [HttpPost] public string Test() { return "value1"; } /// <summary> /// 发起请求调用Test方法 /// </summary> /// <returns></returns> [HttpGet] public async Task<string> PostTest() { SearchReq req = new SearchReq(); req.Name = "zhangshang"; req.Description = "Description"; req.PageSize = 10; req.PageIndex = 1; //包装参数 var reqJson = new StringContent( JsonSerializer.Serialize(req), Encoding.UTF8, Application.Json ); var httpClient = _httpClientFactory.CreateClient(); using var httpResponseMessage = await httpClient.PostAsync("https://localhost:7279/api/Values/Test", reqJson); var readStr = await httpResponseMessage.Content.ReadAsStringAsync(); return readStr; } } }
标签:webapi,set,请求,get,httpClientFactory,req,HttpPost,using,public From: https://www.cnblogs.com/tlfe/p/18345400