加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – WebApi – 请求包含实体主体但没有Content-Type

发布时间:2020-12-16 03:35:15 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试在webApi端点上接受application / x-www-form-urlencoded数据.当我向PostMan发送一个明确设置了此Content-Type标头的请求时,我收到一个错误: The request contains an entity body but no Content-Type header 我的控制器: [HttpPost] [Route("a
我正在尝试在webApi端点上接受application / x-www-form-urlencoded数据.当我向PostMan发送一个明确设置了此Content-Type标头的请求时,我收到一个错误:

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

我的控制器:

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

我究竟做错了什么?

解决方法

如果查看请求消息,您可以看到正在发送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; }
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读