【问题标题】:WebApi - The request contains an entity body but no Content-Type headerWebApi - 请求包含实体主体但没有 Content-Type 标头
【发布时间】:2014-12-02 15:32:13
【问题描述】:

我正在尝试在我的 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);
        }
    }

邮差帽:

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    如果您查看请求消息,您可以看到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' 标头。然后,body(Test)中的值将正确绑定到参数。

    【讨论】:

    • 你就像 WebAPI Badri 的蝙蝠侠。感谢您再次拯救我的一天。
    猜你喜欢
    • 2019-04-30
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-25
    • 1970-01-01
    相关资源
    最近更新 更多