首页新闻找找看学习计划

C#中HttpClient问题"Properties can only be modified before sending the first request"

0
悬赏园豆:20 [已解决问题] 解决于 2018-03-26 09:55

使用HttpClient的C#代码如下:

public class TestClass
{
   private static readonly HttpClient _httpClient = new HttpClient();
   public async Task TestMethod ()
   { 
       //...
       _httpClient.BaseAddress = new Uri("http://xxx");
       //...
    }
}

运行时报错

System.InvalidOperationException: This instance has already started one or more requests. Properties can only be modified before sending the first request.
   at System.Net.Http.HttpClient.CheckDisposedOrStarted()
   at System.Net.Http.HttpClient.set_BaseAddress(Uri value)
dudu的主页 dudu | 高人七级 | 园豆:41258
提问于:2018-03-25 22:09
< >
分享
最佳答案
0

在初始化的时候就定义BaseAddress呗

收获园豆:20
Shendu.CC | 小虾三级 |园豆:1811 | 2018-03-26 09:44

哎呀妈,被dudu老大采纳了,受宠若惊!

Shendu.CC | 园豆:1811 (小虾三级) | 2018-03-26 10:05
private static readonly HttpClient _httpClient = new HttpClient() { BaseAddress = new Uri("http://xxx") };
dudu | 园豆:41258 (高人七级) | 2018-03-26 10:05

@dudu: 是的,没错!

Shendu.CC | 园豆:1811 (小虾三级) | 2018-03-26 10:06
其他回答(3)
0

dudu 老大也有问题咨询呀,帮你顶了!!!

海洋风g | 园豆:224 (菜鸟二级) | 2018-03-25 22:51
0

我还以为java类库~

不清楚你上下文,但堆栈貌似很明白。

不过还是推荐这种低级类库别用了,直接用RestSharp,我写外挂有时都用这玩意儿,认证、序列化等等封装都比较可以。

花飘水流兮 | 园豆:10177 (专家六级) | 2018-03-26 01:26
0
爱编程的大叔 | 园豆:29784 (高人七级) | 2018-03-26 09:28
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册