Back to Aspnetcore

ASP0005: Do not place attribute on method called by route handler lambda

aspnetcore/diagnostics/asp0005.md

latest1.4 KB
Original Source

ASP0005: Do not place attribute on method called by route handler lambda

Value
Rule IDASP0005
CategoryUsage
Fix is breaking or non-breakingNon-breaking

Cause

An attribute was applied to a method definition instead of the route handler in a route handler endpoint.

Rule description

When an endpoint is declared, attributes should be applied to the delegate parameter in order to be effective. For example, the Authorize attribute in the following code sample isn't set on the registered endpoint:

csharp
app.MapGet("/todos/{id}", GetTodoById);

[Authorize]
Todo GetTodoById(int id)
{
  ...
}

The attribute must be placed on the route handler parameter as shown in the following code:

csharp
app.MapGet("/todos/{id}", [Authorize] GetTodoById);

Todo GetTodoById(int id)
{
  ...
}

How to fix violations

To fix a violation of this rule, make sure that endpoint attributes are applied to the route handler parameter:

csharp
app.MapGet("/todos/{id}", [Authorize] (int id) => {});
app.MapGet("/users/{id}", [Authorize] GetUserById);

When to suppress warnings

Do not suppress a warning from this rule. Misplaced attributes can result in unexpected behavior at runtime.