[英]How to add a cookie to a request using HttpClient from IHttpClientFactory
[英]Using named HttpClient from IHttpClientFactory in a custom client
我知道我會因為問這個問題而被釘在十字架上,這個問題之前已經被問過一百萬次了,我 promise 你,我已經看過其中的大部分問題/答案,但我仍然有點卡住了。
這是一個 .NET 標准 2.0 class 庫,支持 ASP.NET Core 6 API。
在我的Program.cs
中,我創建了一個命名的 HttpClient,如下所示:
builder.Services.AddHttpClient("XYZ_Api_Client", config =>
{
var url = "https://example.com/api";
config.BaseAddress = new Uri(url);
});
我有一個將使用此HttpClient
的自定義客戶端,我在Program.cs
中創建了一個 singleton MyCustomClient
,以便我的存儲庫可以使用它。 代碼如下。 這是我卡住的地方,因為我不確定如何將我命名的HttpClient
傳遞到MyCustomClient
中。
builder.Services.AddSingleton(new MyCustomClient(???)); // I think I need to pass the HttpClient to my CustomClient here but not sure how
我的CustomClient
需要使用這個名為XYZ_Api_Client
的HttpClient
來完成它的工作:
public class MyCustomClient
{
private readonly HttpClient _client;
public MyCustomClient(HttpClient client)
{
_client = client;
}
public async Task<bool> DoSomething()
{
var result = await _client.GetAsync();
return result;
}
}
所以我不確定如何將這個命名的HttpClient
傳遞到Program.cs
中的MyCustomClient
中。
你可以直接在你class中注入IHttpClientFactory
,然后將命名的HttpClient
賦值給一個屬性。
注冊工廠和您的自定義客戶端:
builder.Services.AddHttpClient("XYZ_Api_Client", config =>
{
var url = "https://example.com/api";
config.BaseAddress = new Uri(url);
});
// no need to pass anything, the previous line registered IHttpClientFactory in the container
builder.Services.AddSingleton<MyCustomClient>();
然后在你 class 中:
public class MyCustomClient
{
private readonly HttpClient _client;
public MyCustomClient(IHttpClientFactory factory)
{
_client = factory.CreateClient("XYZ_Api_Client");
}
// ...
}
或者,您可以在注冊MyCustomClient
時傳遞命名實例
注冊工廠和您的自定義客戶端:
builder.Services.AddHttpClient("XYZ_Api_Client", config =>
{
var url = "https://example.com/api";
config.BaseAddress = new Uri(url);
});
// specify the factory for your class
builder.Services.AddSingleton<MyCustomClient>(sp =>
{
var factory = sp.GetService<IHttpClientFactory>();
var httpClient = factory.CreateClient("XYZ_Api_Client");
return new MyCustomClient(httpClient);
});
然后在你 class 中:
public class MyCustomClient
{
private readonly HttpClient _client;
public MyCustomClient(HttpClient client)
{
_client = client;
}
// ...
}
您也可以這樣做:
// register the named client with the name of the class
builder.Services.AddHttpClient("MyCustomClient", config =>
{
config.BaseAddress = new Uri("https://example.com/api");
});
// no need to specify the name of the client
builder.Services.AddHttpClient<MyCustomClient>();
AddHttpClient<TClient>(IServiceCollection)
所做的是
將 IHttpClientFactory 和相關服務添加到 IServiceCollection 並配置 TClient 類型和命名的 HttpClient 之間的綁定。 客戶端名稱將設置為 TClient 的全名。
您可以在此處找到完整的文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.