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

后端 未结 3 561
梦如初夏
梦如初夏 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:08

    HttpClient.DefaultRequestHeaders (and BaseAddress) should only be set once, before you make any requests. HttpClient is only safe to use as a singleton if you don't modify it once it's in use.

    Rather than setting DefaultRequestHeaders, set the headers on each HttpRequestMessage you are sending.

    var request = new HttpRequestMessage(HttpMethod.Post, url);
    request.Headers.Accept.Clear();
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
    request.Content = new StringContent("{...}", Encoding.UTF8, "application/json");
    var response = await _client.SendAsync(request, CancellationToken.None);
    

    Replace "{...}" with your JSON.

提交回复
热议问题