dotnet / dotnet/aspnetcore

Create an analyzer that warns when delegates are mapped to GET, DELETE, or HEAD requests and expect a request body

Open
#35,727 2 comments 1 reaction 0 assignees View on GitHub
analyzer area-minimal feature-minimal-actions
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

OpenAPI 3.0 states that GET, DELETE, and HEAD are not allowed to have request body because it does not have defined sematics as per RFC 7231:

https://swagger.io/docs/specification/describing-request-body/

> GET, DELETE and HEAD are no longer allowed to have request body because it does not have defined semantics as per RFC 7231.

We should have an analyzer that warns the user when they annotate delegates mapped to GET, DELETE, or HEAD requests with Accepts/Consumes metadata, as those types of requests typically shouldn't be expecting a request body.

Examples of delegates that should produce a warning:
``` c#
// This has a complex parameter which by default expects a JSON request body
app.MapGet("/thing", (Thing thing) => return Results.Ok());

// This adds accepts metadata indicating it expects a JSON (default) request body in the shape of Thing
app.MapDelete("/thing", (HttpRequest request) => return Results.Ok())
.Accepts();

// This adds accepts metadata via an attribute indicating it expects a JSON request body in the shape of Thing
app.MapGet("/thing", HandleGet);
[Consumes(typeof(Thing), "application/json")]
IResult HandleGet(Thing thing)
{
return Results.Ok();
}
```

Examples of delegates that technically are invalid according to the same rules but the analyzer would likely not produce a warning for as they don't represent an idiomatic form:
``` c#
app.Map("/thing", HandleThingHead);
[Consumes("application/json")]
Task HandleThingHead(HttpContext context, RequestDelegate next)
{
if (context.Request.Method == HttpMethods.Head)
{
context.Response.StatusCode = StatusCodes.Status200OK;
return Task.CompletedTask;
}
return next(context);
}
```

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.