我试图调用的API需要一个具有空主体的POST。我正在使用WCF Web API HttpClient,我找不到正确的代码,将发布一个空的主体。我找到了一些HttpContent.CreateEmpty()方法的引用,但我不认为它是为Web API HttpClient代码,因为我似乎找不到该方法。


我认为如果你的web方法没有参数,或者它们都适合URL模板,它就会自动做到这一点。

例如,这个声明发送空的主体:

  [OperationContract]
  [WebGet(UriTemplate = "mykewlservice/{emailAddress}",
     RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
     BodyStyle = WebMessageBodyStyle.Wrapped)]
  void GetStatus(string emailAddress, out long statusMask);

使用StringContent或ObjectContent派生自HttpContent,或者你可以使用null作为HttpContent:

var response = await client.PostAsync(requestUri, null);

之前做过,保持简单:

Task<HttpResponseMessage> task = client.PostAsync(url, null);

发现:

Task<HttpResponseMessage> task = client.PostAsync(url, null);

向请求体中添加null,该请求体在WSO2上失败。替换为:

Task<HttpResponseMessage> task = client.PostAsync(url, new {});

和工作。


要解决这个问题,请使用下面的例子:

   using (var client = new HttpClient())
            {
                var stringContent = new StringContent(string.Empty);
                stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
                var response = client.PostAsync(url, stringContent).Result;
                var result = response.Content.ReadAsAsync<model>().Result;
            }

如果你不想传递空值,你可以执行以下命令:

Task<HttpResponseMessage> task = httpClient.PostAsync(uri, new StringContent(String.Empty));

但是,除此之外,如上所述,您可以将null作为参数传递进来。