我正在使用 HttpClientFactory 發出 http 請求。
這是我的代碼: -
namespace handleDeviceOperations
{
class Program
{
string operationID = String.Empty;
static async Task Main(string[] args)
{
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
var services = serviceCollection.BuildServiceProvider();
var httpClientFactory = services.GetRequiredService<IHttpClientFactory>();
//Getting operationID from few other lines of code
var httpClientGetOperations = httpClientFactory.CreateClient("getOperations");
var request1 = await httpClientGetOperations.GetAsync("");
var responseMessage1 = await request1.Content.ReadAsStringAsync();
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddHttpClient("getOperations", options =>
{
options.BaseAddress = new Uri("https://myurl.com/events/");
options.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic","Auth_Value");
});
}
}
如您所見,這是我的基本地址:"https://myurl.com/events/"
現在,就在此處提出請求之前:-
var httpClientGetOperations = httpClientFactory.CreateClient("getOperations");
var request1 = await httpClientGetOperations.GetAsync("");
我想將 operationID 添加到基地址的末尾,這樣基地址就變成了這樣:-
"https://myurl.com/events/45872254"
//The string at the end will differ each time
這是一個非常必要的步驟,因為請求完全依賴于 operationID 引數。
uj5u.com熱心網友回復:
options.BaseAddress = new Uri("https://myurl.com/");
...
var id = 45872254;
var request1 = await httpClientGetOperations.GetAsync($"events/{id}");
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/485370.html
標籤:C# 。网 异步等待 dotnet-httpclient httpclientfactory
下一篇:多個消費者不丟失訊息
