如何在ASP.NET Core中使用HttpClient?

How can we use HttpClient in ASP.Net Core?(如何在ASP.NET Core中使用HttpClient?)

本文介绍了如何在ASP.NET Core中使用HttpClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写ASP.NET MVC Core 2.2 Web App。我需要从另一个使用HTTP或HTTPS的Web服务器获取数据。我应该如何操作?

我使用HttpClient编写代码。

我有一个收到消息的控制器,它工作正常,但是,我应该构造HttpClient吗?

[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
    private readonly IHostingEnvironment _env;
    private readonly ILogger _logger;
    private readonly IUpdateService _updateService;

    public MyController(
        IHostingEnvironment env,
        ILogger<MyController> logger,
        IUpdateService updateService)
    {
        _env = env;
        _logger = logger;
        _updateService = updateService;
    }

    // POST api/values
    [HttpPost]
    public async Task<IAsyncResult> Post([FromBody]Update update)
    {
        using (HttpClient Client = new HttpClient())
        {
            HttpResponseMessage result = Client.GetAsync(uri).Result;
            switch (result.StatusCode)
            {
                case HttpStatusCode.Accepted:
                    return true;
                case HttpStatusCode.OK:
                    return true;
                default:
                    return false;
            }
        }
    }
}

推荐答案

Microsoft documentation here.

  1. ConfigureServices中注册HttpClient

    1a.对于typed clients

    services.AddHttpClient<ITypedClientService, TypedClientService>();
    

    1b。对于named clients

    services.AddHttpClient("someClient", c =>
    {
        c.BaseAddress = new Uri("https://someaddress.com/");
    });
    

    1c.对于Basic usage

    services.AddHttpClient();
    
  2. HttpClient注入您的控制器。

    [ApiController]
    public class BotController : ControllerBase
    {
        ...
    

    2a.对于typed clients

        public BotController(..., ITypedClientService httpClient, ...)
        {
            ...
            _httpClient = httpClient;
            ...
        }
    

    2b。对于named clients

        public BotController(..., IHttpClientFactory clientFactory, ...)
        {
            ...
            _httpClient = clientFactory.createClient("someClient");
            ...
        }
    

    2c.对于Basic usage

        IHttpClientFactory _clientFactory
    
        public BotController(..., IHttpClientFactory clientFactory, ...)
        {
            ...
            _clientFactory = clientFactory; 
            ...
        }
    
        [HttpPost]
        public async Task<IActionResult> Post([FromBody]Update update)
        {
            ...
            var request = new HttpRequestMessage(
                HttpMethod.Get, 
                "https://someaddress.com/api/resource");
            request.Headers.Add("Accept", "application/vnd.github.v3+json");
            request.Headers.Add("User-Agent", "YourApp");
            var client = _clientFactory.createClient();
            var response = await client.SendAsync(request);
            ...
        }
    
<2-0]不要构造自己,新是胶水。让HttpClientFactory和框架管理生存期和实例化。

注意, 使用基本用法可以避免为已定义的客户端配置策略的好处。

这篇关于如何在ASP.NET Core中使用HttpClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在ASP.NET Core中使用HttpClient?

基础教程推荐