【问题标题】:Elegant way to use Multiple SwaggerResponses使用多个 SwaggerResponses 的优雅方式
【发布时间】:2019-05-09 06:32:45
【问题描述】:

我将在我的控制器上使用这些属性:

    [SwaggerResponse((int)HttpStatusCode.OK, typeof(GetAutotopupConfigurationResponse))]
    [SwaggerResponse((int)HttpStatusCode.BadRequest, typeof(ErrorResponse), BadRequestMessage)]
    [SwaggerResponse((int)HttpStatusCode.Unauthorized, typeof(ErrorResponse), InvalidCredentiasMessage)]
    [SwaggerResponse((int)HttpStatusCode.Forbidden, typeof(ErrorResponse), UserNoRightsMessage)]
    [SwaggerResponse((int)HttpStatusCode.NotFound, typeof(ErrorResponse), AutopopupNotFoundMessage)]
    [SwaggerResponse((int)HttpStatusCode.InternalServerError, typeof(ErrorResponse), InternalServerErrorMessage)]

如何简化逻辑并减少代码量或以某种方式使其更灵活?

【问题讨论】:

标签: c# .net asp.net-mvc asp.net-web-api swagger


【解决方案1】:

编辑这个答案适用于Asp.Net-Core,但也可能对这个问题有用。

如果您使用Swashbuckle,您可以使用IOperationFilter 和反射来定位特定端点并以编程方式应用响应。

可以使用IOperationFilter 将 InternalServerError 应用于服务中的所有端点。下面是一个例子:

public class ServerErrorResponseOperationFilter : IOperationFilter
{            
    // Applies the specified operation. Adds 500 ServerError to Swagger documentation for all endpoints            
    public void Apply(Operation operation, OperationFilterContext context)
    {
        // ensure we are filtering on controllers
        if (context.MethodInfo.DeclaringType.BaseType.BaseType == typeof(ControllerBase)
            || context.MethodInfo.ReflectedType.BaseType == typeof(Controller))
        {
            operation.Responses.Add("500", new Response { Description = "Server Error" });
        }                        
    }
}

您需要设置 Swagger 才能使用这些过滤器。您可以通过添加设置来做到这一点:

services.AddSwaggerGen(swag =>
{
    swag.SwaggerDoc("v1", new Info { Title = "Docs", Version = "v1" });

    // add swagger filters to document default responses
    swag.OperationFilter<ServerErrorResponseOperationFilter>();
});

您可以使用其他过滤器来应用 401 Unauthorized、403 Forbidden 等。您甚至可以使用 Reflection 为带有 [HttpPost] 装饰的操作添加 201 Created,您可以对其他 Http 属性执行类似的操作。

如果您有 401、403 和 500 的过滤器,可以稍微整理一下您的控制器。您仍然需要为反射无法处理的某些方法添加属性。使用这种方法,我发现我只需要添加一个或 2 个属性,通常是 [ProcudesResponseType((int)HttpStatusCode.BadRequest)][ProcudesResponseType((int)HttpStatusCode.NotFound)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    相关资源
    最近更新 更多