AspNetCore.Docs/aspnetcore/diagnostics/asp0004.md

42 lines
1.6 KiB
Markdown

---
title: "ASP0004: Do not use action results with route handlers"
description: "Learn about analysis rule ASP0004: Do not use action results with route handlers"
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/asp0004
---
# ASP0004: Do not use action results with route handlers
| | Value |
|-|-|
| **Rule ID** |ASP0004|
| **Category** |Usage|
| **Fix is breaking or non-breaking** |Non-breaking|
## Cause
A route handler delegate returns a value that implements <xref:Microsoft.AspNetCore.Mvc.IActionResult>.
## Rule description
Route handler endpoints do not support executing MVC's `IActionResult` instances. Returning an `IActionResult` that doesn't implement `IResult` results in serializing the result instance rather than executing the result.
```csharp
app.MapGet("/todos/{id}", (int id) => new JsonResult(new Todo { .. }));
```
## How to fix violations
To fix a violation of this rule, make sure that endpoint's route handler returns an <xref:Microsoft.AspNetCore.Http.IResult> type by using the <xref:Microsoft.AspNetCore.Http.Results> extension methods.
```csharp
app.MapGet("/todos/{id}", (int id) => Results.Json(new Todo { .. }));
```
## When to suppress warnings
Do ***not*** suppress a warning from this rule. Returning an `IActionResult` that doesn't implement `IResult` results in serializing the result instance rather than executing the result.