我正在编写ASP.Net MVC Core 2.2 Web App。我需要使用HTTP或HTTPS从另一个Web服务器获取数据。我该怎么办?
我使用HttpClient
编写了代码。
我有一个获取消息的Controller,它工作正常,但是,我应该构造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;
}
}
}
}
答案 0 :(得分:1)
在HttpClient
中注册ConfigureServices
。
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);
...
}
不要自己构造HttpClient
,新的东西就是胶水。让HttpClientFactory
和框架管理生命周期和实例化。
注意, 使用基本用法,您可以避免为已定义的客户端配置策略的好处。