dotnet / dotnet/aspnetcore

Suggest the use of the Results class to produce responses instead of manually writing to the HttpResponse

Open
#35,761 2 comments 1 reaction 0 assignees View on GitHub
analyzer area-minimal feature-minimal-actions Priority:2
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

This sample:

```C#
app.MapGet("/todos/{id}", (int id, HttpContext context) =>
{
var todo = db.Find(id);
if (todo is null)
{
context.Response.StatusCode = 400;
return Task.CompletedTask;
}

return context.Response.WriteAsJsonAsync(todo);
});
```

Gets changed to this:

```C#
app.MapGet("/todos/{id}", (int id) =>
{
var todo = db.Find(id);
if (todo is null)
{
return Results.BadRequest();
}

return Results.Ok(todo);
});
```

This goes for setting the content type as well:

```C#
app.MapGet("/content", (HttpContext context) =>
{
var content = @"top";

context.Response.ContentType = "application/xml";
return context.Response.WriteAsync(content);
});
```

Suggested to:

```C#
app.MapGet("/content", () =>
{
var content = @"top";

return Results.Text(content, "application/xml");
});
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.