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

Value
Rule ID ASP0005
Category Usage
Fix is breaking or non-breaking Non-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:

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:

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:

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.