繁体   English   中英

如何接受 JSON 作为其内容类型的无主体 GET 请求?

[英]How to accept a bodyless GET request with JSON as it's content type?

在迁移到 ASP.NET Core 2.1 后,我们意识到我们的 API 的一些消费者正在发送Content-Type header 设置为application/json的 GET 请求。 可悲的是,这些请求过去没有被拒绝(即使他们应该拒绝),但这仍然是一个突破性的变化。

由于我们的消费者需要自己解决这个问题,这需要一些时间,我们希望暂时接受这些请求,这样我们就不会等待这个问题。

框架(正确)拒绝请求并显示以下错误消息: "A non-empty request body is required."

动作如下所示:

[Route("api/file/{id:guid}")]
public async Task<IActionResult> Get(Guid id)
{
     // Some simple code here
}

未到达操作内的代码,因为错误在到达操作之前已被抛出(由于请求不正确)。

@Nkosi 的解决方案产生了相同的响应:

[HttpGet("api/file/{id:guid}")]
public async Task<IActionResult> Get([FromRoute]Guid id)
{
     // Some simple code here
}

消费者使用的 (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
));

删除"Content-Type: application/json",行会将请求变为有效请求,因此我们有 99.9% 的把握确定添加此 header 是作恶者。

考虑在管道的早期删除中间件中的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM