You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swashbuckle.AspNetCore 10.1.7如何自动文档化401/403等标准HTTP响应?

问题:Swashbuckle.AspNetCore 10.1.7自动文档化标准HTTP响应(401/403)的方案

我在.NET中搭配Swashbuckle.AspNetCore 10.1.7使用新版本OpenAPI,当前Swagger安全配置如下:

services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.Http,
        Scheme = "Bearer",
        BearerFormat = "JWT"
    });

    options.AddSecurityRequirement(document => new OpenApiSecurityRequirement
    {
        [new OpenApiSecuritySchemeReference("Bearer", document)] = []
    });
});

该配置可正常工作,Swagger UI已显示认证按钮,但存在响应文档问题:带有[Authorize]特性的端点返回401 Unauthorized时,Swagger UI显示为“401 – Undocumented”,尽管认证已生效且端点能正确返回401。

我希望采用全局方案自动文档化200、401、403等标准响应,而非逐个控制器/操作添加[ProducesResponseType]特性;试过IOperationFilter但不确定是否为Swashbuckle 10.x的推荐方案,或是否有内置方式实现此需求。请问在Swashbuckle.AspNetCore 10.1.7中,无需手动添加[ProducesResponseType],自动文档化标准HTTP响应(尤其是401/403)的正确或推荐方式是什么?IOperationFilter是该版本唯一合适的解决方案吗?


解决方案

Swashbuckle.AspNetCore 10.x并没有内置的全局自动添加标准HTTP响应的功能,自定义IOperationFilter是官方推荐且最适合的全局方案。通过实现这个过滤器,可以自动为带有[Authorize]特性的操作添加401、403响应文档,同时也能全局添加200等通用响应。

1. 实现自定义IOperationFilter

创建一个过滤器类,逻辑如下:

  • 检查操作或其所在控制器是否带有[Authorize]特性,若是则添加401、403响应
  • 为未定义响应的操作默认添加200响应
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class StandardResponseFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        // 判断操作是否需要授权
        var hasAuthorize = context.MethodInfo.DeclaringType?.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any() ?? false;
        hasAuthorize |= context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any();

        if (hasAuthorize)
        {
            operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized - 未提供有效令牌或令牌已过期" });
            operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden - 无权限访问该资源" });
        }

        // 为未定义响应的操作添加默认200响应
        if (!operation.Responses.ContainsKey("200"))
        {
            operation.Responses.Add("200", new OpenApiResponse { Description = "OK - 请求成功" });
        }
    }
}

2. 注册过滤器

在AddSwaggerGen配置中注册这个自定义过滤器:

services.AddSwaggerGen(options =>
{
    // 原有的安全配置
    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.Http,
        Scheme = "Bearer",
        BearerFormat = "JWT"
    });

    options.AddSecurityRequirement(document => new OpenApiSecurityRequirement
    {
        [new OpenApiSecuritySchemeReference("Bearer", document)] = []
    });

    // 注册自定义响应过滤器
    options.OperationFilter<StandardResponseFilter>();
});

补充说明

  • 若需要扩展其他标准响应(如400、500),可直接在过滤器中添加对应逻辑
  • 如果个别操作需要覆盖全局响应定义,仍可通过添加[ProducesResponseType]特性实现,特性定义的响应优先级高于过滤器添加的内容

内容的提问来源于stack exchange,提问作者Mahyar Niavand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 07:17:32