.net core 2.1 - httpclientfactory - Error - This instance has already started one or more requests

时间:2018-12-03 13:21:14

标签: httpclient asp.net-core-webapi asp.net-core-2.1

We are using .net core 2.1 and using httpclientfactory in our application.

We have registered service using services.AddTransient in startup.cs

While calling first API from code everything is working fine.

When we call second API its throwing "This instance has already started one or more requests. Properties can only be modified before sending the first request."

I received error while setting timeout for _httpClient.

private readonly HttpClient _httpClient;

public ApiClient(IHttpClientFactory httpClientFactory)
{
     _httpClient = httpClientFactory.CreateClient();
}   

public async Task<IResponse> PutJsonAsync<IResponse, IRequest>(Uri uri, int? timeOut)
{
    SetTimeout(timeOut);
    var response = await _httpClient.PutAsync(uri, content).ConfigureAwait(false);
    ...
    ...
}

private void SetTimeout(int? timeOut)
{
    if (timeOut.HasValue)
    {
        _httpClient.Timeout = new TimeSpan(0, 0, 0, timeOut.Value);
    }
}

Requirement is that I need to set timeout for each API.

How we can achieve it?

0 个答案:

没有答案