首页 > 解决方案 > 在 Swagger 中生成响应错误 - .netCore Api

问题描述

为了处理所有错误,我使用 ErrorHandlingMiddleware。在任何我想要的地方抛出异常(我的实现异常),我定义类型(枚举)和错误消息。我的问题是如何在 swagger 中生成这种类型的错误,因为 swagger 只知道控制器返回类型值。并且招摇在方法中仅生成响应(200)bcs仅返回Ok();

[HttpPost("login")]
public async Task<IActionResult> Test(LoginRequest req)
{
    if (user.Banned)
    {
        throw new BadRequestHorseedoException(ErrorCode.BANNED, "User is banned");
    }

    return Ok();
}

标签: c#restasp.net-core.net-coreswagger

解决方案


您可以ProducesResponseType在方法上使用属性。您的代码可能如下所示:

[HttpPost("login")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Test(LoginRequest req)

推荐阅读