Home > Enterprise >  How to post an empty body to POST endpoint
How to post an empty body to POST endpoint

Time:11-09

I have an endpoint that accepts [FromBody] object param1, looks like this:

public IActionResult PostStuff([FromBody] object param1)
{

}

However, I am trying to have this [FromBody] param to be optional. So sometimes I might want to pass it JSON, and sometimes I do not. Here's my API call code

private void CallPostAPI(string body)
{
    string url = "....../api/poststuff";

    var httpClientHandler = new HttpClientHandler {UseDefaultCredentials = true};

    using (var client = new HttpClient(httpClientHandler){BaseAddress = new Uri(url})
    {
        HttpRequestMessage request = new HttpRequestMessage
        {
              Method = HttpMethod.Post
        };

        if (body !=null)
        {
             request.content = new StringContent(body, Encoding.UTF8, "application/json");
        }

        var results = client.SendAsync(request);

        var response = results.Result;

    }
}

This works great when I have JSON body, however, how would I go about sending an empty BODY?

Errors I get if trying to send it without content:

StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:

Thanks.

CodePudding user response:

You have to explicitly enable it in your Configure (startup):

  services.AddControllersWithViews(opt =>
  {
       opt.AllowEmptyInputInBodyModelBinding = true;
  });

then you can send an empty body:

enter image description here

and end up with a null:

enter image description here

CodePudding user response:

try this, it was tested, you don't need any extra configuration

if (body ==null) body=string.Empty
request.content = new StringContent(body, Encoding.UTF8, "application/json");
  • Related