dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.23k stars 9.95k forks source link

Don't require a controller with an action to return RFC-7807 errors #19051

Closed mariusGundersen closed 4 years ago

mariusGundersen commented 4 years ago

According to the documentation on error handling Two steps are needed to handle errors in asp.net core web apis: 1) Add the app.UseExceptionHandler("/error"); midldeware in Startup.cs 2) Create a controller with an action like this:

[ApiController]
public class ErrorController : ControllerBase
{
    [Route("/error")]
    public IActionResult Error() => Problem();
}

It seems uneccessairly convoluted and verbose to create a controller action just to call a method available in the BaseController class. Couldn't the response also be handled by the middleware? Why is a controller needed for this scenario?

I have tested a bit, and it seems like this codeblock does roughly the same job:

app.UseExceptionHandler(e => e.Run(async c =>
{
    var factory = c.RequestServices.GetRequiredService<ProblemDetailsFactory>();
    var problem = factory.CreateProblemDetails(c, statusCode: 500);
    c.Response.StatusCode = problem.Status ?? 500;
    c.Response.ContentType = "application/json";
    await c.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(problem));
}));

It would be great to have this (or something similar but more robust) be included in ASP.NET core out of the box, to handle the very common scenario of returning a json error formatted according to RFC-7807.

javiercn commented 4 years ago

@mariusGundersen thanks for contacting us.

We will triage your request appropriately and get back to you.

mkArtakMSFT commented 4 years ago

Thanks for contacting us. This is not something we plan to do.