How can we use HttpClient in ASP.Net Core?(如何在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.
在
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();
将
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); ... }
HttpClientFactory
和框架管理生存期和实例化。
注意, 使用基本用法可以避免为已定义的客户端配置策略的好处。
这篇关于如何在ASP.NET Core中使用HttpClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在ASP.NET Core中使用HttpClient?
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01