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

如何配置Swashbuckle为401错误指定不同媒体类型?

实现Swashbuckle为特定HTTP状态码配置不同媒体类型

当然可以实现,下面是两种常用的配置方式:

1. 直接通过方法注解指定媒体类型

你可以给ProducesResponseType注解添加ContentType参数,单独为401错误指定text/html类型,400错误保持默认的application/json(继承自控制器的[Produces("application/json")])。修改后的方法代码如下:

[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
// 为401指定text/html媒体类型
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized, ContentTypes = new[] { "text/html" })]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[HttpPost]
public async Task<ActionResult<MyModel>> PostAsync(MyRequest myRequest)
{
    // 方法逻辑
}

2. 全局配置(文档过滤器)

如果多个接口都需要为401错误统一设置text/html类型,可以通过Swashbuckle的文档过滤器批量修改。

步骤1:实现IDocumentFilter

创建一个自定义过滤器类,遍历所有接口操作的响应,找到状态码为401的条目,修改其媒体类型:

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class CustomResponseMediaTypeFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        foreach (var path in swaggerDoc.Paths.Values)
        {
            foreach (var operation in path.Operations.Values)
            {
                // 检查是否存在401响应
                if (operation.Responses.TryGetValue("401", out var response))
                {
                    // 清空原有媒体类型,添加text/html
                    response.Content.Clear();
                    response.Content.Add("text/html", new OpenApiMediaType());
                }
            }
        }
    }
}

步骤2:注册过滤器

在Program.cs(或Startup.cs)中注册这个过滤器:

builder.Services.AddSwaggerGen(c =>
{
    c.DocumentFilter<CustomResponseMediaTypeFilter>();
    // 其他Swagger配置...
});

这样配置后,Swagger UI里所有接口的401错误都会显示text/html媒体类型,400错误则保持控制器默认的application/json。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:45:36