简体   繁体   中英

ASP.NET Core error handler without HTTP verb throws Swashbuckle exception

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM