如何接受内容类型为 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 设置为 [=15= 的 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();
});
//...
}
迁移到 ASP.NET Core 2.1 后,我们发现 API 的一些消费者正在发送 Content-Type
header 设置为 [=15= 的 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();
});
//...
}