【发布时间】:2014-10-03 14:08:23
【问题描述】:
我正在使用 .NET 4.0 的 ASP.NET Web API 客户端库(Microsoft.AspNet.WebApi.Client 版本 4.0.30506.0)。
我需要发送带有请求正文的 HTTP DELETE。我将其编码如下:
using (var client = new HttpClient())
{
client.BaseAddress = Uri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// I would normally use httpClient.DeleteAsync but I can't because I need to set content on the request.
// For this reason I use httpClient.SendAsync where I can both specify the HTTP DELETE with a request body.
var request = new HttpRequestMessage(HttpMethod.Delete, string.Format("myresource/{0}", sessionId))
{
var data = new Dictionary<string, object> {{"some-key", "some-value"}};
Content = new ObjectContent<IDictionary<string, object>>(data, new JsonMediaTypeFormatter())
};
var response = await client.SendAsync(request);
// code elided
}
对于每个 Fiddler,请求正文永远不会被序列化:
DELETE http://localhost:8888/myApp/sessions/blabla123 HTTP/1.1
Accept: application/json
Content-Type: application/json; charset=utf-8
Host: localhost:8888
Content-Length: 38
Expect: 100-continue
来自服务器的响应:
HTTP/1.1 408 Request body incomplete
Date: Sun, 10 Aug 2014 17:55:17 GMT
Content-Type: text/html; charset=UTF-8
Connection: close
Cache-Control: no-cache, must-revalidate
Timestamp: 13:55:17.256
The request body did not contain the specified number of bytes. Got 0, expected 38
我尝试了许多变通方法,包括将要序列化的类型更改为其他类型、自己使用 JsonSerialize 进行序列化、将 HTTP DELETE 更改为 PUT 等...
没有任何效果。任何帮助将不胜感激。
【问题讨论】:
-
ObjectContent类型是什么? -
顺便说一句,您是否尝试过使用
DeleteAsync而不将内容类型设置为application-json? -
ObjectContent 泛型类型是 IDictionary
。本质上是一组键值对。 -
DeleteAsync 不支持传递任何内容。
-
我将 HttpRequestMessage 的 Content 属性设置为
new ObjectContent<IDictionary<string, object>>(data, new JsonMediaTypeFormatter())。我确实尝试了 StringContent ,但这也不起作用。当我序列化我的测试数据以放入字符串时,它看起来像这样{ "some-key", "some-value" }
标签: c# json asp.net-web-api http-delete