当我使用HttpClient
(System.Net.Http)DeleteAsync
功能和检索Content.ReadAsStringAsync()
内容我总是得到null
返回。HttpClient.DeleteAsync和Content.ReadAdStringAsync总是返回null
我试过GET
,POST
和PUT
- 他们总是返回一些结果。
这里是我的代码:
HttpClient _client = new HttpClient();
_client.BaseAddress = new Uri("http://httpbin.org/");
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = _client.DeleteAsync("/delete").Result;
string res = await response.Content.ReadAsStringAsync();
return await JsonConvert.DeserializeObjectAsync<T>(res);
我总是null
返回。
然而,这一切的工作原理:
GET:
HttpResponseMessage response = _client.GetAsync("/get").Result;
string res = await response.Content.ReadAsStringAsync();
return await JsonConvert.DeserializeObjectAsync<T>(res);
POST:
HttpResponseMessage response = _client.PostAsync("/post", new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")).Result;
string res = await response.Content.ReadAsStringAsync();
return await JsonConvert.DeserializeObjectAsync<T>(res);
PUT:
HttpResponseMessage response = _client.PutAsync("/put", new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")).Result;
string res = await response.Content.ReadAsStringAsync();
return await JsonConvert.DeserializeObjectAsync<T>(res);
但DeleteAsync()
和ReadAsStringAsync()
总是返回我null
。
根据RFC你必须在返回状态码200 OK时返回body。
您是否尝试过使用[菲德勒(http://fiddler2.com/)看电线上发生了什么? –
不应该在结果上有所作为,但是有什么理由阻止(在'DeleteAsync'上调用'.Result')而不是等待它? – cremor
@cremor新人的错误。 – Gaui