The API I'm trying to call requires a POST with an empty body. I'm new to using the WCF Web API HttpClient, and I can't seem to find the right code that will post with an empty body. I found references to some HttpContent.CreateEmpty() method, but I don't think it’s for the Web API HttpClient code since I can't seem to find that method.
Use StringContent
or ObjectContent
which derive from HttpContent
or you can use null
as HttpContent
:
var response = await client.PostAsync(requestUri, null);
Did this before, just keep it simple:
Task<HttpResponseMessage> task = client.PostAsync(url, null);
Have found that:
Task<HttpResponseMessage> task = client.PostAsync(url, null);
Adds null to the request body, which failed on WSO2. Replaced with:
Task<HttpResponseMessage> task = client.PostAsync(url, new {});
And worked.
null
content and look at the content found in the HttpRequestMessage
, I seem to be getting a length of zero bytes.
To solve this problem, use this example:
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;
}
I think it does that automagically if your web method has no parameters or they all fit into URL template.
For example this declaration sends empty body:
[OperationContract]
[WebGet(UriTemplate = "mykewlservice/{emailAddress}",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
void GetStatus(string emailAddress, out long statusMask);
Success story sharing
HttpContent
class? Should we at least provide something (even an empty string) to make a http post?null
as theHttpContent
, this will send no body in the request, e.g.var response = await client.PostAsync(requestUri, null);
System.Net.Http
in version 5.0.0.0 has still no nullableHttpContent
parameter, sonull
should be not allowed. But it (still) seems to work. I could passnull!
.