HttpClient.SendAsync不发送请求正文

Phi*_*ppe 5 c# json http-delete asp.net-web-api

我正在使用.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
}
Run Code Online (Sandbox Code Playgroud)

Per 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等等...

没有任何效果.任何帮助将非常感激.

Phi*_*ppe 2

我解决了这个问题,尽管它没有意义。我注意到,如果我将调用更改为 HTTP PUT 或 POST,它仍然无法将内容序列化为请求正文。这很奇怪,因为之前的 PUT 和 POST 都是成功的。在对框架库进行了大量调试(使用 Reflector)之后,我终于找到了唯一剩下的“不同”的地方。

我正在使用 NUnit 2.6.2。我的测试的结构是:

[Test]
async public void Test()
{
  // successful HTTP POST and PUT calls here
  // successful HTTP DELETE with request body here (after 
  //       moving it from the TearDown below)
}

[TearDown]
async public void TerminateSession()
{
  // failed HTTP DELETE with request body here
}
Run Code Online (Sandbox Code Playgroud)

为什么这在拆解中失败,但在测试本身中却失败了?我不知道。TearDown 属性或使用 async 关键字(因为我等待异步调用)是否发生了问题?

我不确定是什么导致了这种行为,但我现在知道我可以提交带有请求正文的 HTTP DELETE(如问题中的代码示例中所述)。

另一个有效的解决方案如下:

[Test]
async public void Test()
{
  // create and use an HttpClient here, doing POSTs, PUTs, and GETs
}

// Notice the removal of the async keyword since now using Wait() in method body
[TearDown]
public void TerminateSession()
{
  // create and use an HttpClient here and use Wait().
  httpClient.SendAsync(httpRequestMessage).Wait();
}
Run Code Online (Sandbox Code Playgroud)