Httpclient此实例已启动一个或多个请求.只能在发送第一个请求之前修改属性 [英] Httpclient This instance has already started one or more requests. Properties can only be modified before sending the first request

查看:1155
本文介绍了Httpclient此实例已启动一个或多个请求.只能在发送第一个请求之前修改属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在.Net Core 2.1中创建一个应用程序,并且正在使用HTTP客户端进行Web请求.问题是我必须发送并行调用以节省时间,并且为此我正在使用Task.WhenAll()方法,但是当我按下此方法时,我收到错误消息此实例已启动一个或多个请求.只能修改属性在发送第一个请求之前".以前,我使用RestSharp,一切都很好,但是我想使用httpclient.这是代码:

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.WhenAll() method but when I hit this method I get the error "This instance has already started one or more requests. Properties can only be modified before sending the first request" Previously I was using RestSharp and everything was fine but I want to use httpclient. Here is the code:

public async Task<User> AddUser(string email)
{
    var url = "user/";
    _client.BaseAddress = new Uri("https://myWeb.com/");
    _client.DefaultRequestHeaders.Accept.Clear();
    _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants."application/json"));
    _client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
    var json = new {email = email }
    var response = await _client.PostAsJsonAsync(url,json);
    if (response .IsSuccessStatusCode)
    { ....

这里是构造函数:

private readonly HttpClient _httpClient;

public UserRepository(HttpClient httpClient)
{         
    _httpClient = httpClient;
}

方法调用:

var user1 = AddUser("user@user.com");
var user2 = AddUser("test@test.com");

await Task.WhenAll(user1, user2);

这是启动配置:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

那么我在做什么错了?我需要用AddTransient()更改AddSingleton还是有其他问题.响应后我还需要使用一个问题_client.Dispose(),因为我遵循的教程没有使用dispose方法,因此我对此不太困惑.

So what am I doing wrong? Do I need to change AddSingleton with AddTransient() or is there any other issue. One more question do I need to use _client.Dispose() after the response because the tutorial which I followed didn't use dispose method so I am little confused in that.

推荐答案

HttpClient.DefaultRequestHeaders(和BaseAddress)仅应设置一次,然后再进行任何请求. HttpClient只有在使用后不对其进行修改的情况下,才可以安全地用作单例.

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.

而不是设置DefaultRequestHeaders,而是在要发送的每个HttpRequestMessage上设置标头.

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);

用您的JSON替换"{...}".

这篇关于Httpclient此实例已启动一个或多个请求.只能在发送第一个请求之前修改属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆