gpt4 book ai didi

c# - 使用 HttpClientFactory .net Core 2.1 对每个请求进行身份验证

转载 作者:行者123 更新时间:2023-11-30 12:19:56 27 4
gpt4 key购买 nike

我应该如何使用 HttpClientFactory 返回其 uri 和凭据在调用时确定的 HttpClient 实例?

现有代码如下所示:

var httpClientHandler = new HttpClientHandler()
{
Credentials = new NetworkCredential(userName, password),
};
HttpClient client = new HttpClient(httpClientHandler);
client.BaseAddress = new Uri(_appSetting.ServiceURI);

最佳答案

启动类中的ConfigureServices方法

services.AddHttpClient("github", c =>
{
//c.BaseAddress = new Uri("https://api.github.com/");
c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");

}).ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler()
{
UseDefaultCredentials = true,
Credentials = new NetworkCredential("", ""),
};
});

你的 Controller 看起来像这样

private readonly IHttpClientFactory _httpClientFactory;

public DataProController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}

[HttpGet]
public async Task<ActionResult> Get()
{
var client = _httpClientFactory.CreateClient("github");

client.BaseAddress = new Uri("https://api.github.com/");

string result = await client.GetStringAsync("/");
return Ok(result);
}

使用 httpclientfactory 时,您可能无法在运行时设置网络凭据,可能需要在启动类中进行设置。您可以在此处找到有关此问题的信息。 https://github.com/aspnet/HttpClientFactory/issues/71

关于c# - 使用 HttpClientFactory .net Core 2.1 对每个请求进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54477722/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com