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

如何在ASP.NET中为API响应头数据编写Swagger文档

在Swagger中记录响应头的分页信息

默认情况下,ProducesResponseType只能帮你在Swagger中定义响应体结构,但无法直接声明响应头。要让Swagger展示你返回的X-Pagination分页响应头,需要通过自定义Swagger操作过滤器来实现,具体步骤如下:

1. 定义自定义响应头属性(可选但更灵活)

先创建一个属性类,用来标记接口需要返回的响应头信息:

[AttributeUsage(AttributeTargets.Method)]
public class ProducesResponseHeaderAttribute : Attribute
{
    public ProducesResponseHeaderAttribute(string name, Type type, int statusCode = StatusCodes.Status200OK)
    {
        Name = name;
        Type = type;
        StatusCode = statusCode;
    }

    public string Name { get; }
    public Type Type { get; }
    public int StatusCode { get; }
}

2. 实现Swagger操作过滤器

编写一个实现IOperationFilter的类,读取自定义属性并将响应头信息添加到Swagger文档中:

public class ResponseHeaderFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var responseHeaderAttrs = context.MethodInfo.GetCustomAttributes<ProducesResponseHeaderAttribute>();

        foreach (var attr in responseHeaderAttrs)
        {
            // 确保对应状态码的响应存在
            if (!operation.Responses.TryGetValue(attr.StatusCode.ToString(), out var response))
            {
                response = new OpenApiResponse();
                operation.Responses[attr.StatusCode.ToString()] = response;
            }

            // 添加响应头定义
            response.Headers ??= new Dictionary<string, OpenApiHeader>();
            response.Headers[attr.Name] = new OpenApiHeader
            {
                Description = "分页元数据",
                Schema = context.SchemaGenerator.GenerateSchema(attr.Type, context.SchemaRepository)
            };
        }
    }
}

3. 注册过滤器到Swagger配置

在项目的Swagger配置代码中(通常是Program.cs或Startup.cs),注册这个自定义过滤器:

builder.Services.AddSwaggerGen(c =>
{
    c.OperationFilter<ResponseHeaderFilter>();
    // 其他Swagger相关配置...
});

4. 在API接口上标记自定义属性

修改你的接口方法,添加自定义的ProducesResponseHeader属性,指定响应头名称和对应的分页模型类型:

[ProducesResponseType(typeof(List<string>), StatusCodes.Status200OK)]
[ProducesResponseHeader("X-Pagination", typeof(PaginationModel))]
[HttpGet]
public async Task<IActionResult> test()
{
    var paginationModel = new PaginationModel()
    {
        CurrentPage = 12,
        TotalCount = 500,
        TotalPages = 10
    };

    HttpContext.Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationModel));

    return Ok(new List<string>());
}

完成以上步骤后,重新启动项目查看Swagger文档,就能在对应接口的200 OK响应下看到X-Pagination响应头的结构说明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:17:16