dotnet / dotnet/aspnetcore

HttpMethodOverrideMiddleware is missing HEAD on GET requests.

Open
#11,654 2 comments 0 reactions 0 assignees View on GitHub
affected-few area-middleware enhancement severity-minor
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

As of right now, the [**HttpMethodOverrideMiddleware**](https://github.com/aspnet/AspNetCore/blob/c95ee2b051814b787b07f55ff224d03d550aafeb/src/Middleware/HttpOverrides/src/HttpMethodOverrideMiddleware.cs) only support overriding methods for `POST` requests, and when the method is overridable by a `HEAD` method the body is still returned.

Currently kestrel prevents body writing to `HEAD` requests but since method overriding happens later in a middleware, Kestrel has no chance to prevent the output.

Unfortunately there are some clients that doesn't support `HEAD` verb and there are 2 issues with the current **HttpMethodOverrideMiddleware**

1. Only support override for `POST` verbs while `HEAD` should be allowed on ANY type of request.
2. It doesn't prevent body writing on `HEAD`.

To solve both issue I propose the following change to `HttpMethodOverrideMiddleware` `Invoke` method:

```c#
public async Task Invoke(HttpContext context)
{
var xHttpMethodOverrideValue = context.Request.Headers[xHttpMethodOverride];
// New path that checks explicitly for HEAD verb.
if (string.Equals(xHttpMethodOverrideValue, HttpMethods.Head, StringComparison.OrdinalIgnoreCase))
{
context.Request.Method = HttpMethods.Head;
// Prevents body to include data, this also sets Content-Length to 0.
context.Response.Body = Stream.Null;
}
// Previous behavior.
else if (string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase))
{
// ... current code
}
await _next(context);
}
```

If there's interest in updating the current middleware I can submit a PR

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.