Post an empty body to REST API via HttpClient

C#WcfHttpclientWcf Web-Api

C# Problem Overview


The API I'm trying to call requires that I do a POST but with an empty body. I'm new to using the WCF Web API HttpClient and I can't seem to find out the write code that would do a post with an empty body. I find references to some HttpContent.CreateEmpty() method, but I don't think that is for the Web API HttpClient code since I can't seem to find that method.

C# Solutions


Solution 1 - C#

Use StringContent or ObjectContent which derive from HttpContent or you can use null as HttpContent:

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

Solution 2 - C#

Did this before, just keep it simple:

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

Solution 3 - C#

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.

Solution 4 - C#

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

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyan RinaldiView Question on Stackoverflow
Solution 1 - C#Alexander ZeitlerView Answer on Stackoverflow
Solution 2 - C#OgglasView Answer on Stackoverflow
Solution 3 - C#Ryan TuckView Answer on Stackoverflow
Solution 4 - C#abolfazl mousaviView Answer on Stackoverflow
Solution 5 - C#Ivan G.View Answer on Stackoverflow