简体   繁体   English

没有 HTTP 动词的 ASP.NET Core 错误处理程序引发 Swashbuckle 异常

[英]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.不要使用 HTTP 方法属性标记错误处理程序操作方法,例如 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:但是,当我遵循该建议(而不是[HttpGet("/error")] )时,我从 Swashbuckle 收到此错误:

Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException: Ambiguous HTTP method for action - ErrorController.Error. Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException:操作的 HTTP 方法不明确 - ErrorController.Error。 Actions require an explicit HttpMethod binding for Swagger/OpenAPI 3.0操作需要 Swagger/OpenAPI 3.0 的显式 HttpMethod 绑定

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.文档中建议的原因是允许任何类型的 HTTP 请求在发生错误时到达错误处理程序。 For example, if you mark it as [HttpGet] , it will not be able to handle errors in POST requests.例如,如果您将其标记为[HttpGet] ,它将无法处理 POST 请求中的错误。

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)]为了[ApiExplorerSettings(IgnoreApi = true)]与 Swagger 配合使用,您可以使用以下属性标记控制器(甚至特定操作): [ApiExplorerSettings(IgnoreApi = true)]

This will cause Swashbuckle to not generate metadata for it and to not display it in the Swagger UI.这将导致 Swashbuckle 不为其生成元数据,也不会在 Swagger UI 中显示它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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