HttpClient.DeleteAsync和Content.ReadAdStringAsync始终返回null

时间:2013-07-14 15:13:46

标签: c# rest httpclient json.net async-await

当我在DeleteAsync (System.Net.Http)中使用HttpClient函数并使用Content.ReadAsStringAsync()检索内容时,我总是{ {1}}已退回。

我已经对nullGETPOST进行了同样的尝试 - 他们总是会返回一些结果。

这是我的代码:

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

发表:

HttpResponseMessage response = _client.GetAsync("/get").Result;
string res = await response.Content.ReadAsStringAsync();
return await JsonConvert.DeserializeObjectAsync<T>(res);

PUT:

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

但是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()

根据RFC,你必须在返回状态码200 OK时返回身体。

3 个答案:

答案 0 :(得分:5)

您的代码从不检查StatusCode的消息响应。与WebClient不同,当StatusCode不在2xx范围内时,HttpClient不会抛出。

我敢打赌,如果您检查HttpResponseMessage.StatusCode / HttpResonseMessage.ReasonPhrase值,您会发现服务器返回的代码不是200。

例如:

HttpClient _client = new HttpClient();
_client.BaseAddress = new Uri("http://httpbin.org/");
...
var response = await _client.DeleteAsync("/delete");
if (response.IsSuccessStatusCode)
{
    var result=await response.Content.ReadAsStringAsync();
    ....
}

如果响应状态不是成功代码,您也可以调用EnsureSuccessStatusCode方法抛出异常:

HttpClient _client = new HttpClient();
_client.BaseAddress = new Uri("http://httpbin.org/");
...
var response = await _client.DeleteAsync("/delete");
response.EnsureSuccessStatusCode();
var result=await response.Content.ReadAsStringAsync();

修改

顺便说一句,在.NET 4.5上运行以下命令会返回一个正文:

        var  _client = new HttpClient();
        _client.BaseAddress = new Uri("http://httpbin.org/");
        var response = await _client.DeleteAsync("/delete");
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);

        }

添加Accept标题没有任何区别

答案 1 :(得分:0)

我有相同的情况......现在我不知道DeleteAsync的方法重载,它接受像post这样的内容参数。所以我将API从Delete切换到Post。

答案 2 :(得分:-2)

您知道吗?

base_address +  relative_address  

"http://www.youdomain.com/myservice/"  + "/test"  = "/test".
  

这就是你什么都没得到的原因