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

如何用Swashbuckle基于JsonResult响应自动生成OpenAPI文档?

如何让Swashbuckle为JsonResult自动生成OpenAPI文档

Swashbuckle默认能识别ActionResult<T>这类强类型返回值并生成详细的API文档,但直接返回JsonResult(尤其是包含匿名对象时),因为无法自动识别返回数据的结构,默认不会生成完整的模型文档。你可以通过以下两种方式解决:

方法一:显式声明返回模型(推荐)

既然返回的是固定结构的JSON(包含data和message字段),可以先定义一个通用的强类型响应模型,再通过[ProducesResponseType]特性告诉Swashbuckle返回的具体类型。

步骤1:定义通用响应模型

public class ApiResponse<T>
{
    public T Data { get; set; }
    public string Message { get; set; }
}

步骤2:修改Action并添加特性

[HttpGet]
[ProducesResponseType(typeof(ApiResponse<List<Student>>), StatusCodes.Status200OK)]
public JsonResult GetStudents()
{
    var response = new ApiResponse<List<Student>>
    {
        Data = CollegeRepository.Students,
        Message = "success"
    };

    return new JsonResult(response)
    {
        StatusCode = StatusCodes.Status200OK
    };
}

这样Swashbuckle就能基于ApiResponse<List<Student>>生成包含data和message字段的详细文档了。

方法二:自定义Swashbuckle过滤器解析JsonResult

如果不想定义强类型模型,可以写一个自定义的IOperationFilter,通过反射解析JsonResult中匿名对象的结构,手动为Swashbuckle生成Schema。

步骤1:创建自定义过滤器

using Microsoft.AspNetCore.Mvc;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;

public class JsonResultSchemaFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var returnType = context.MethodInfo.ReturnType;
        if (returnType != typeof(JsonResult) && !returnType.IsSubclassOf(typeof(JsonResult)))
            return;

        var schemaGenerator = context.SchemaGenerator;
        var schemaRepository = context.SchemaRepository;

        // 构造示例中匿名对象对应的Schema
        var responseSchema = new OpenApiSchema
        {
            Type = "object",
            Properties = new Dictionary<string, OpenApiSchema>
            {
                ["data"] = schemaGenerator.GenerateSchema(typeof(List<Student>), schemaRepository),
                ["message"] = new OpenApiSchema { Type = "string" }
            },
            Required = new HashSet<string> { "data", "message" }
        };

        // 更新200状态码的响应Schema
        operation.Responses[StatusCodes.Status200OK.ToString()].Content["application/json"].Schema = responseSchema;
    }
}

步骤2:注册过滤器

在Program.cs(或Startup.cs)中添加过滤器:

builder.Services.AddSwaggerGen(c =>
{
    c.OperationFilter<JsonResultSchemaFilter>();
});

注意:这种方式需要手动维护Schema结构,如果返回的匿名对象有变化,过滤器也要同步修改,不如强类型模型灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:32:45