61 lines
1.8 KiB
Markdown
61 lines
1.8 KiB
Markdown
---
|
|
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: captainsafia
|
|
monikerRange: '>= aspnetcore-6.0'
|
|
ms.author: riande
|
|
ms.date: 10/21/2021
|
|
no-loc: [Home, Privacy, Kestrel, appsettings.json, "ASP.NET Core Identity", cookie, Cookie, Blazor, "Blazor Server", "Blazor WebAssembly", "Identity", "Let's Encrypt", Razor, SignalR]
|
|
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.
|