In the docs for error handling there's this:
Warning
Don't mark the error handler action method with HTTP method attributes, such as HttpGet. Explicit verbs prevent some requests from reaching the action method.
So it recommends this:
[ApiController]
public class ErrorController : ControllerBase
{
//[HttpGet] <-- docs say not to do this
[Route("/error")]
public IActionResult Error() => Problem();
}
However when I follow that advice (instead of [HttpGet("/error")]
) I get this error from Swashbuckle:
Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException: Ambiguous HTTP method for action - ErrorController.Error. Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0
Obviously when I include the verb, it works.
Can someone explain the reasoning behind that advice in the docs?
CodePudding user response:
The reason for the advice in the docs is to allow any kind of HTTP request to reach the error handler if an error occurs. For example, if you mark it as [HttpGet]
, it will not be able to handle errors in POST requests.
In order to get this to play nice with Swagger, you can mark the controller (or even the specific action) with this attribute:
[ApiExplorerSettings(IgnoreApi = true)]
This will cause Swashbuckle to not generate metadata for it and to not display it in the Swagger UI.