如何从 jsonresult 响应自动生成 OpenAPI 文档?

问题描述 投票:0回答:1

Swashbuckle可以根据代码自动生成API文档(带有详细返回模型)

[HttpGet]
public ActionResult<List<Student>> GetStudents()
{
    return CollegeRepository.Students;
}

有什么方法可以让Swashbuckle自动生成API文档JsonResult吗?

[HttpGet]
public JsonResult GetStudents()
{
    var json = new JsonResult(new
    {
        data = CollegeRepository.Students,
        message = "success"
    });

    json.StatusCode = StatusCodes.Status200OK;

    return json;
}
c# asp.net-core swagger openapi swashbuckle
1个回答
0
投票

你可以做类似下面的事情。

public static void SaveSwaggerJson(this IServiceProvider provider)
{
    ISwaggerProvider sw = provider.GetRequiredService<ISwaggerProvider>();
    OpenApiDocument doc = sw.GetSwagger("v1", null, "/");
    string swaggerFile = doc.SerializeAsJson(Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0);
    var root = AppDomain.CurrentDomain.BaseDirectory ?? "~";
    string swaggerDir = Path.Combine(root, "swagger");
    if(!Directory.Exists(swaggerDir))
    {
        Directory.CreateDirectory(swaggerDir);
    }
    string fileName = DateTime.Now.ToString("MM_dd_yyyy_hh_mm_ss_") + "swaggerfile.json";
    string filePath = Path.Combine(swaggerDir, fileName);
    File.WriteAllText(filePath, swaggerFile);
}
© www.soinside.com 2019 - 2024. All rights reserved.