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.
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 inStartup.cs
2) Create a controller with an action like this: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:
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.