對于 asp.net 網路表單應用程式,我正在嘗試從 httpclientfactory 生成 httpclient。但是,回傳的 httpclient 沒有我在 GetHttpClientFactory 方法中配置的配置(基地址和標頭)。
public static class HttpClientFactory
{
private static IHttpClientFactory _httpClientFactory;
private const string _ClientKey = "MyClient";
public static IHttpClientFactory GetHttpClientFactory()
{
if (_httpClientFactory != null)
{
return _httpClientFactory;
}
var serviceCollection = new ServiceCollection();
serviceCollection.AddHttpClient(_ClientKey, client =>
{
client.BaseAddress = new Uri("http://localhost:36338");
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("User-Agent", "Demo");
})
.ConfigurePrimaryHttpMessageHandler(() =>
new HttpClientHandler
{
Credentials = new NetworkCredential("accountname", "password")
});
var serviceProvider = serviceCollection.BuildServiceProvider();
_httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
return _httpClientFactory;
}
}
這是我呼叫工廠生成客戶端的地方。
protected async void Page_Load(object sender, EventArgs e)
{
//RegisterAsyncTask(new PageAsyncTask(GetDivisions));
var loggerFactory = LoggerFactory.Create(builder => {
builder.AddFilter("Microsoft", LogLevel.Warning);
});
var httpClient = HttpClientFactory.GetHttpClientFactory();
var commonServices = new ServiceWrapper(loggerFactory.CreateLogger<ServiceWrapper>(), httpClient);
var divisions = await commonServices.GetDivisions();
foreach (var d in divisions)
AddTableRow(Table1, d.Id, d.Name);
}
每次我發出 Web 請求時,都會收到“提供了無效請求 URI”的例外。
uj5u.com熱心網友回復:
我很確定您在CreateClient沒有提供客戶名稱的情況下打電話。在你的下一個嘗試ServiceWrapper:
// 1. not sure how the second parameter of ServiceWrapper is called
// 2. Possibly make HttpClientFactory._ClientKey public so no need for magic string
var result = httpClientFactory.CreateClient("MyClient");
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/410220.html
標籤:
上一篇:將影像插入到asp.net頁面
