AspNetCore.Docs/aspnetcore/diagnostics/asp0005.md

60 lines
1.6 KiB
Markdown
Raw Normal View History

---
title: "ASP0005: Do not place attribute on method called by route handler lambda"
description: "Learn about analysis rule ASP0005: Do not place attribute on method called by route handler lambda"
author: safia
monikerRange: '>= aspnetcore-6.0'
ms.author: riande
ms.date: 10/21/2021
uid: diagnostics/asp0005
---
# 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](xref:Microsoft.AspNetCore.Authorization.AuthorizeAttribute) 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.