3 回答
TA贡献1796条经验 获得超4个赞
启动类中的配置服务方法
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("", ""),
};
});
您的控制器将如下所示
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
TA贡献1815条经验 获得超10个赞
您可以创建一个身份验证委派处理程序,如下所示:
public class AuthenticationHttpMessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
// Get the token or other type of credentials here
// string scheme = ... // E.g. "Bearer", "Basic" etc.
// string credentials = ... // E.g. formatted token, user/password etc.
request.Headers.Authorization =
new AuthenticationHeaderValue(scheme, credentials);
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
然后将其添加到 HttpClient 构建器和 DI 容器中:
services
.AddTransient<AuthenticationHttpMessageHandler>()
.AddHttpClient("MyClient")
.AddHttpMessageHandler<AuthenticationHttpMessageHandler>();
然后使用 IHttpClientFactory 创建 HttpClient 实例。
这种方法的核心优点是您可以清楚地将关注点分开。您无需接触主处理程序,无需手动管理客户端创建,而是利用了工厂的全部功能及其构建器扩展方法。身份验证处理程序自然注入管道中,并为每个请求添加授权。通过抽象出凭据的源并使处理程序依赖于某些 IAuthenticationProvider 抽象,可以进一步增强此处理程序,这只需要 DI 配置,而无需接触 HttpClient 配置代码。
TA贡献1851条经验 获得超3个赞
如果使用 .net 依赖关系注入,则可以将一个类的配置添加到设置代码中:
services
.AddTransient<DataLoader>()
.AddHttpClient<DataLoader>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
{
Credentials = new NetworkCredential(LoadUsernameFromConfig(), LoadPasswordFromSecureLocation())
});
现在添加,DI 会将使用此凭据的 注入到类中:HttpClientDataLoader
public class DataLoader
{
private readonly HttpClient httpClient;
public DataLoader(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task LoadData(string tableName)
{
var json = await httpClient.GetStringAsync("https://protected.example.com/json");
...
}
}
- 3 回答
- 0 关注
- 157 浏览
添加回答
举报