SB2*_*055 5 asp.net-mvc asp.net-web-api asp.net-web-api2
我正在尝试接受application/x-www-form-urlencoded我的webApi端点上的数据.当我向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);
}
}
Run Code Online (Sandbox Code Playgroud)
POSTMAN上限:

我究竟做错了什么?
Bad*_*dri 11
如果您查看请求消息,您可以看到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; }
}
Run Code Online (Sandbox Code Playgroud)
相反,如果您坚持绑定string Body,请不要选择x-www-form-urlencoded选项卡.而是选择原始选项卡并发送正文=Test.当然,在这种情况下,您必须手动添加`Content-Type:application/x-www-form-urlencoded'标头.然后,正文中的值(Test)将正确绑定到参数.

| 归档时间: |
|
| 查看次数: |
11666 次 |
| 最近记录: |