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

5

我正在尝试在我的WebApi端点上接受application/x-www-form-urlencoded数据。当我发送一个具有显式设置此Content-Type头的PostMan请求时,我会收到错误:

请求包含实体主体,但没有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应用程序:

POSTMAN应用程序:

enter image description here

我错在哪里了?

1个回答

13

如果您查看请求消息,您可以看到 Content-Type 标头是这样发送的。

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

因此,您手动添加了 Content-Type 标头并且由于选择了 x-www-form-urlencoded 选项卡,POSTMAN 也会添加它。

如果您删除已添加的标头,则应该可以正常工作。我的意思是,您不会收到错误,但由于简单类型参数 [FromBody]string Body,绑定将无法工作。您需要将操作方法设置为如下方式。

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

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

输入图像描述


你就像WebAPI领域的蝙蝠侠,Badri。再次感谢你救了我的一天。 - SB2055

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接