欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#通过HttpClient访问WebAPI,获取返回结果

程序员文章站 2024-02-20 10:59:28
...

HttpClient的使用方法有很多,不再赘述。
1.Web API

	[Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet("requesttest")]
        public IActionResult RequestTest()
        {
            return Ok("返回的信息");
        }
    }

2.Web APP

public class IndexModel : PageModel
{
    private IHttpClientFactory _httpClientFactory;
    public IndexModel(IHttpClientFactory httpClientFactory)//通过依赖注入方式,注意在startup类中注册   services.AddHttpClient();
    {
        _httpClientFactory = httpClientFactory;
    }
    public string Result { get; set; }
    public async Task OnGetAsync()
    {
        var client = _httpClientFactory.CreateClient();
        var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5100/api/values/requesttest");
        var respond = await client.SendAsync(request).Result.Content.ReadAsStringAsync();//
        Result = respond;//显示
    }
}
相关标签: web api