Httpclient This instance has already started one or more requests. Properties can only be modified before sending the first request

后端 未结 3 565
梦如初夏
梦如初夏 2021-02-03 22:29

I am creating an application in .Net Core 2.1 and I am using http client for web requests. The issue is I have to send parallel calls to save time and for that I am using Task.W

3条回答
  •  野的像风
    2021-02-03 23:22

    The issue is caused by resetting BaseAddress and headers for the same instance of the httpclient.

    I tried

    if (_httpClient.BaseAddress == null) 
    

    but I am not keen on this.

    In my opinion, a better soloution is to use the httpclientFactory. This will terminate and garbage collect the instance of the httpclient after its use.

    private readonly IHttpClientFactory _httpClientFactory;
    public Foo (IHttpClientFactory httpClientFactory) 
    {
    _httpClientFactory = httpClientFactory;
    }
    public  httpresponse Bar ()
    {
    _httpClient = _httpClientFactory.CreateClient(command.ClientId);
    
    using var response = await _httpclient.PostAsync(uri,content);
    return response;
    // here as there is no more reference to the _httpclient, the garbage collector will clean 
    // up the _httpclient and release that instance. Next time the method is called a new 
    // instance of the _httpclient is created
    }
    
    

提交回复
热议问题