dotnet / dotnet/aspnetcore

Minimal API filters won't run endpoint handler when 4xx/5xx status code is already set

Open
#60,659 4 comments 0 reactions 0 assignees View on GitHub
area-minimal
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Describe the bug

Minimal API filters don't seem to run the request delegate if a non-OK status code is set before the filter (by middleware or preceding filters).

https://github.com/dotnet/aspnetcore/blob/8b77ff5251b9a90b9a937330bd27bfaf71b701f4/src/Http/Routing/src/RequestDelegateFilterPipelineBuilder.cs#L34-L38

**An example in which the current behaviour becomes problematic** is when an authentication handler sets a 4xx status code (e.g., after an unsuccesful attempt to authenticate the request), but continues the request to reach the endpoint handler which might produce some sort of authentication error message. This request never reaches the endpoint handler, and produces a blank response.

### Expected Behavior

Expected filters to always run the request delegate, regardless of the status code that is set before the filter.

### Steps To Reproduce

```csharp
static void Main()
{
var builder = WebApplication.CreateBuilder();

var app = builder.Build();

app.Use(async (ctx, next) =>
{
ctx.Response.StatusCode = StatusCodes.Status400BadRequest;
await next(ctx);
});

app.MapGet("1", () => "1");
app.MapGet("2", () => "2").AddEndpointFilter(async (ctx, next) => await next(ctx));

app.Run();
}
```

Notice how,
- `GET /1` produces the response `1`, as expected.
- `GET /2` produces an empty response, instead of `2`.

### Exceptions (if any)

_No response_

### .NET Version

9.0.200

### Anything else?

_No response_

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.