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

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


现有代码如下所示:


var httpClientHandler = new HttpClientHandler()

    {

        Credentials = new NetworkCredential(userName, password),

    };

HttpClient client = new HttpClient(httpClientHandler);

client.BaseAddress = new Uri(_appSetting.ServiceURI);


幕布斯7119047
浏览 158回答 3
3回答

慕的地8271018

启动类中的配置服务方法&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;services.AddHttpClient("github", c =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //c.BaseAddress = new Uri("https://api.github.com/");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).ConfigurePrimaryHttpMessageHandler(() =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new HttpClientHandler()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; UseDefaultCredentials = true,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Credentials = new NetworkCredential("", ""),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });您的控制器将如下所示&nbsp;private readonly IHttpClientFactory _httpClientFactory;&nbsp; &nbsp; &nbsp; &nbsp; public DataProController(IHttpClientFactory httpClientFactory)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _httpClientFactory = httpClientFactory;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; [HttpGet]&nbsp; &nbsp; &nbsp; &nbsp; public async Task<ActionResult> Get()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var client = _httpClientFactory.CreateClient("github");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; client.BaseAddress = new Uri("https://api.github.com/");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string result = await client.GetStringAsync("/");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Ok(result);&nbsp; &nbsp; &nbsp; &nbsp; }使用 httpclientfactory 时,您可能无法在运行时设置网络凭据,并且可能需要在启动类中进行设置。您可以在此处找到有关此问题的信息。https://github.com/aspnet/HttpClientFactory/issues/71

动漫人物

您可以创建一个身份验证委派处理程序,如下所示:public class AuthenticationHttpMessageHandler : DelegatingHandler&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; protected override async Task<HttpResponseMessage> SendAsync(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HttpRequestMessage request,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CancellationToken cancellationToken)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Get the token or other type of credentials here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // string scheme = ... // E.g. "Bearer", "Basic" etc.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // string credentials = ... // E.g. formatted token, user/password etc.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; request.Headers.Authorization =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new AuthenticationHeaderValue(scheme, credentials);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }然后将其添加到 HttpClient 构建器和 DI 容器中:&nbsp;services&nbsp; &nbsp; &nbsp;.AddTransient<AuthenticationHttpMessageHandler>()&nbsp; &nbsp; &nbsp;.AddHttpClient("MyClient")&nbsp; &nbsp; &nbsp;.AddHttpMessageHandler<AuthenticationHttpMessageHandler>();然后使用 IHttpClientFactory 创建 HttpClient 实例。这种方法的核心优点是您可以清楚地将关注点分开。您无需接触主处理程序,无需手动管理客户端创建,而是利用了工厂的全部功能及其构建器扩展方法。身份验证处理程序自然注入管道中,并为每个请求添加授权。通过抽象出凭据的源并使处理程序依赖于某些 IAuthenticationProvider 抽象,可以进一步增强此处理程序,这只需要 DI 配置,而无需接触 HttpClient 配置代码。

皈依舞

如果使用 .net 依赖关系注入,则可以将一个类的配置添加到设置代码中:services&nbsp; &nbsp; .AddTransient<DataLoader>()&nbsp; &nbsp; .AddHttpClient<DataLoader>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler(){&nbsp; &nbsp; Credentials = new NetworkCredential(LoadUsernameFromConfig(), LoadPasswordFromSecureLocation())});现在添加,DI 会将使用此凭据的 注入到类中:HttpClientDataLoader&nbsp; &nbsp; public class DataLoader&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; private readonly HttpClient httpClient;&nbsp; &nbsp; &nbsp; &nbsp; public DataLoader(HttpClient httpClient)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.httpClient = httpClient;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public async Task LoadData(string tableName)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var json = await httpClient.GetStringAsync("https://protected.example.com/json");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP