【问题标题】:ASP.NET Core 3.1 get method body breaks the request [duplicate]ASP.NET Core 3.1 get 方法体中断请求[重复]
【发布时间】:2020-08-27 21:20:47
【问题描述】:

问题发生在 ASP.NET Core 3.1 Web API 控制器上。我在控制器中有一个方法,[HttpGet] 属性和[FromBody] 仅用于参数:

[HttpGet]
public async Task<ActionResult> GetMessages([FromBody] MessageRM messagesRequest)

这个方法期望接收一个请求模型:

public class MessageRM
{
    public int RegionID { get; set; }
    public int? LastMessageID { get; set; }
    public int? StartMessageID { get; set; }
    public int? PageSize { get; set; }
}

当我在没有正文的情况下对该方法发出 get 请求时,返回结果是:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"|f6d2c92d-47865e9e3ad9a87d."}

这完全出乎意料。有一种感觉我错过了一些重要的东西,当我通过身体时这种感觉增加了。首先使用'{}',然后完全模拟我的请求对象。这些请求中的任何一个都包含“application/json”内容类型标头。两次相同的响应:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|f6d2c92e-47865e9e3ad9a87d.","errors":{"$":["The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."]}}

有什么建议吗?

【问题讨论】:

  • 据我所知get方法不支持body。例如,您应该使用 POST 或 PUT。
  • 另请阅读this

标签: asp.net api http .net-core


【解决方案1】:

将 [HttpGet] 更改为 [HttpPost] 并发出 POST 请求而不是 GET。

【讨论】:

  • 是的,已经测试过了,工作正常。但我仍然对原因感到好奇。您能否添加更多详细信息。这是绕过错误还是在某处有此规范。一些指向 msdn 的链接,其中明确写入:“GET IS NOT ALLOWED TO HAVE A BODY”?
  • @hitpoint 作为链接问题的答案说明,RFC 没有明确禁止在 GET 请求中使用主体,但也没有赋予它任何语义重要性,这意味着服务器的大多数实现者-side 框架忽略 GET 请求的主体。
猜你喜欢
  • 2021-04-09
  • 2018-03-03
  • 2021-12-07
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
相关资源
最近更新 更多