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

如何为Scalar全局配置多端点通用响应类型?

Scalar全局配置通用响应的解决方案

Scalar作为OpenAPI UI工具,依赖最终生成的OpenAPI规范文档展示接口信息,因此你可以复用类似Swagger的OperationFilter方案来全局添加通用响应,无需为每个端点手动标注ProducesResponseType。

实现步骤

  1. 调整原有的OperationFilter
    将你之前的DynamicResponseOperationFilter修改为适配自己的异常类,替换对应的响应Schema类型:
public class DynamicResponseOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        // 自动提取接口200响应的返回类型
        var type = context.MethodInfo.ReturnType;
        if (type.IsGenericType && typeof(Task).IsAssignableFrom(type))
            type = type.GetGenericArguments().First();

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ActionResult<>))
            type = type.GetGenericArguments().First();

        if (type != null)
        {
            operation.Responses["200"] = new OpenApiResponse
            {
                Description = "OK",
                Content = new Dictionary<string, OpenApiMediaType>
                {
                    ["application/json"] = new OpenApiMediaType
                    {
                        Schema = context.SchemaGenerator.GenerateSchema(type, context.SchemaRepository)
                    }
                }
            };
        }

        // 为带[Authorize]的接口添加401响应
        var hasAuthorizeAttribute = HasAuthorizeAttribute(context.MethodInfo);
        if (hasAuthorizeAttribute)
        {
            operation.Responses.Add("401", new OpenApiResponse
            {
                Description = "Unauthorized",
                Content = new Dictionary<string, OpenApiMediaType>
                {
                    ["application/json"] = new OpenApiMediaType
                    {
                        Schema = context.SchemaGenerator.GenerateSchema(typeof(MyUnauthorizedExceptionClass), context.SchemaRepository)
                    }
                }
            });
        }

        // 全局添加500响应
        operation.Responses.Add("500", new OpenApiResponse
        {
            Description = "Internal Server Error",
            Content = new Dictionary<string, OpenApiMediaType>
            {
                ["application/json"] = new OpenApiMediaType
                {
                    Schema = context.SchemaGenerator.GenerateSchema(typeof(MyExceptionClass), context.SchemaRepository)
                }
            }
        });
    }

    private bool HasAuthorizeAttribute(MethodInfo methodInfo)
    {
        // 检查方法是否带[Authorize]特性
        bool hasAuthorizeOnMethod = methodInfo.GetCustomAttributes(true)
            .OfType<AuthorizeAttribute>()
            .Any();
        if (hasAuthorizeOnMethod) return true;

        // 检查控制器是否带[Authorize]特性
        var controllerType = methodInfo.DeclaringType;
        return controllerType?.GetCustomAttributes(true)
            .OfType<AuthorizeAttribute>()
            .Any() ?? false;
    }
}
  1. 配置SwaggerGen生成带全局响应的OpenAPI文档
    在Program.cs中注册该过滤器,确保生成的OpenAPI文档包含这些通用响应:
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(opt =>
{
    opt.OperationFilter<DynamicResponseOperationFilter>();
});
  1. 配置Scalar UI读取OpenAPI文档
    通过NuGet安装Scalar.AspNetCore包后,在Program.cs中配置Scalar指向Swagger生成的OpenAPI端点:
services.AddScalarApiReference(options =>
{
    options
        .AddEndpoint("v1", "/swagger/v1/swagger.json")
        .WithTitle("你的API名称")
        .WithDefaultHttpClient("Axios");
});

// 启用Scalar UI访问端点
app.MapScalarApiReference();

原理说明

Scalar本身不直接处理接口响应的全局配置,它只负责渲染已生成的OpenAPI规范文档。因此只要通过SwaggerGen的OperationFilter完成全局响应的注入,Scalar就会自动展示这些通用响应,效果和你之前用Swagger时完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 04:13:11