3 回答

TA貢獻(xiàn)1796條經(jīng)驗 獲得超4個贊
啟動類中的配置服務(wù)方法
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 時,您可能無法在運行時設(shè)置網(wǎng)絡(luò)憑據(jù),并且可能需要在啟動類中進(jìn)行設(shè)置。您可以在此處找到有關(guān)此問題的信息。https://github.com/aspnet/HttpClientFactory/issues/71

TA貢獻(xiàn)1815條經(jīng)驗 獲得超10個贊
您可以創(chuàng)建一個身份驗證委派處理程序,如下所示:
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 構(gòu)建器和 DI 容器中:
services
.AddTransient<AuthenticationHttpMessageHandler>()
.AddHttpClient("MyClient")
.AddHttpMessageHandler<AuthenticationHttpMessageHandler>();
然后使用 IHttpClientFactory 創(chuàng)建 HttpClient 實例。
這種方法的核心優(yōu)點是您可以清楚地將關(guān)注點分開。您無需接觸主處理程序,無需手動管理客戶端創(chuàng)建,而是利用了工廠的全部功能及其構(gòu)建器擴(kuò)展方法。身份驗證處理程序自然注入管道中,并為每個請求添加授權(quán)。通過抽象出憑據(jù)的源并使處理程序依賴于某些 IAuthenticationProvider 抽象,可以進(jìn)一步增強(qiáng)此處理程序,這只需要 DI 配置,而無需接觸 HttpClient 配置代碼。

TA貢獻(xiàn)1851條經(jīng)驗 獲得超3個贊
如果使用 .net 依賴關(guān)系注入,則可以將一個類的配置添加到設(shè)置代碼中:
services
.AddTransient<DataLoader>()
.AddHttpClient<DataLoader>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
{
Credentials = new NetworkCredential(LoadUsernameFromConfig(), LoadPasswordFromSecureLocation())
});
現(xiàn)在添加,DI 會將使用此憑據(jù)的 注入到類中: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 關(guān)注
- 188 瀏覽
添加回答
舉報