[英]How to accept a bodyless GET request with JSON as it's content type?
After migrating to ASP.NET Core 2.1 we have realized that some consumers of our API are sending GET requests with the Content-Type
header set to application/json
.在迁移到 ASP.NET Core 2.1 后,我们意识到我们的 API 的一些消费者正在发送
Content-Type
header 设置为application/json
的 GET 请求。 Sadly, these requests have not been rejected in the past (even though they should have), nevertheless this still is a breaking change..可悲的是,这些请求过去没有被拒绝(即使他们应该拒绝),但这仍然是一个突破性的变化。
Since our consumers need to fix this issue on their end, and this will take some time, we would like to temporarily accept these requests so we're not stuck waiting for this.由于我们的消费者需要自己解决这个问题,这需要一些时间,我们希望暂时接受这些请求,这样我们就不会等待这个问题。
The framework (correctly) rejects the request with the following error message: "A non-empty request body is required."
框架(正确)拒绝请求并显示以下错误消息:
"A non-empty request body is required."
The action looks like this:动作如下所示:
[Route("api/file/{id:guid}")]
public async Task<IActionResult> Get(Guid id)
{
// Some simple code here
}
The code inside the action isn't being reached as the error is already been thrown before it reaches the action (due to the incorrect request).未到达操作内的代码,因为错误在到达操作之前已被抛出(由于请求不正确)。
@Nkosi's solution resulted in the same response: @Nkosi 的解决方案产生了相同的响应:
[HttpGet("api/file/{id:guid}")]
public async Task<IActionResult> Get([FromRoute]Guid id)
{
// Some simple code here
}
The (PHP) cURL that the consumer uses is this:消费者使用的 (PHP) cURL 是这样的:
$ch = curl_init(self::API_URL."/file/".$id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Application: APPKey ".$this->AppKey,
"Authorization: APIKey ".$this->ApiKey
));
Removing the "Content-Type: application/json",
line turns the request into a valid requests, so we're 99.9% sure that the addition of this header is the evildoer.删除
"Content-Type: application/json",
行会将请求变为有效请求,因此我们有 99.9% 的把握确定添加此 header 是作恶者。
Consider removing the header in a middleware early in the pipeline.考虑在管道的早期删除中间件中的 header。
public void Configure(IApplicationBuilder app) {
app.Use(async (context, next) => {
var request = context.Request;
var method = request.Method;
IHeaderDictionary headers = request.Headers;
string key = "Content-Type";
if (method == "GET" && request.Headers.ContainsKey(key)) {
headers.Remove(key);
}
// Call the next delegate/middleware in the pipeline
await next();
});
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.