WebApi. The request contains the body of the object, but not the Content-Type header

I am trying to accept data application/x-www-form-urlencoded

on my webApi endpoint. When I submit a request with a PostMan that explicitly contains this Content-Type header, I get the error:

The request contains the body of the object, but not the 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("flatout2050@gmail.com", Body);
            return Request.CreateResponse(HttpStatusCode.OK, messages);
        } catch (Exception e) {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
        }
    }

      

POSTMAN cover:

enter image description here

What am I doing wrong?

+3


source to share


1 answer


If you look at the request message, you can see the header is Content-Type

sent this way.

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

So you add the header Content-Type

manually and POSTMAN adds that as well, since you selected the x-www-form-urlencoded tab.

If you remove the added header it should work. I mean you won't get an error, but the binding won't work because of the simple type parameter [FromBody]string Body

. You will need an 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 linking to string Body

, don't select the x-www-form-urlencoded tab. Instead, select the raw tab and submit the body =Test

. Of course, in this case you need to manually add the header `Content-Type: application / x-www-form-urlencoded '. Then the value in the body (Test) will be correctly bound to the parameter.

enter image description here

+6


source







All Articles