WebApi - 请求包含实体主体但没有Content-Type标头

时间:2014-10-08 04:00:51

标签: asp.net-mvc asp.net-web-api asp.net-web-api2

我试图在我的webApi端点上接受application/x-www-form-urlencoded数据。当我向PostMan发送一个明确设置了此Content-Type标头的请求时,出现错误:

  

请求包含实体主体但没有Content-Type标头

我的控制器:

    [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上限:

enter image description here

我做错了什么?

1 个答案:

答案 0 :(得分:10)

如果查看请求消息,您可以看到Content-Type标头正在发送。

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

因此,您手动添加Content-Type标题,并且POSTMAN也添加了该标题,因为您已选择了x-www-form-urlencoded标签。

如果删除已添加的标题,则应该可以使用。我的意思是你不会得到错误,但由于简单的类型参数[FromBody]string Body,绑定将不起作用。你需要有这样的动作方法。

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

相反,如果您坚持绑定到string Body,请不要选择x-www-form-urlencoded标签。而是选择原始选项卡并发送=Test的正文。当然,在这种情况下,您必须手动添加`Content-Type:application / x-www-form-urlencoded'标头。然后,正文中的值(Test)将正确绑定到参数。

enter image description here

相关问题