Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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."

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:

[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:

$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.

like image 973
Timmeh Avatar asked Nov 04 '19 14:11

Timmeh


1 Answers

Consider removing the header in a middleware early in the pipeline.

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();
    });

    //...
}
like image 50
Nkosi Avatar answered Oct 20 '22 09:10

Nkosi