Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi - The request contains an entity body but no Content-Type header

I'm trying to accept application/x-www-form-urlencoded data on my webApi endpoint. When I send a request with PostMan that has this Content-Type header explicitly set, I get an error:

The request contains an entity body but no Content-Type header

My Controller:

    [HttpPost]
    [Route("api/sms")]
    [AllowAnonymous]
    public HttpResponseMessage Subscribe([FromBody]string Body) { // ideally would have access to both properties, but starting with one for now
        try {
            var messages = _messageService.SendMessage("[email protected]", Body);
            return Request.CreateResponse(HttpStatusCode.OK, messages);
        } catch (Exception e) {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
        }
    }

The POSTMAN cap:

enter image description here

What am I doing wrong?

like image 609
SB2055 Avatar asked Oct 08 '14 04:10

SB2055


1 Answers

If you look at the request message, you can see that Content-Type header is being sent like this.

Content-Type: application/x-www-form-urlencoded, application/x-www-form-urlencoded

So, you are adding the Content-Type header manually and POSTMAN is adding that as well, since you have selected the x-www-form-urlencoded tab.

If you remove the header you have added, it should work. I mean you will not get an error but then binding will not work because of the simple type parameter [FromBody]string Body. You will need to have the action method like this.

public HttpResponseMessage Subscribe(MyClass param) { // Access param.Body here }
public class MyClass
{
   public string Body { get; set; }
}

Instead, if you insist on binding to string Body, do not choose the x-www-form-urlencoded tab. Instead choose the raw tab and send the body of =Test. Of course, in this case, you have to manually add the `Content-Type: application/x-www-form-urlencoded' header. Then, the value in the body (Test) will be correctly bound to the parameter.

enter image description here

like image 82
Badri Avatar answered Oct 20 '22 15:10

Badri