如何让 swagger 在 .net core web api 中使用自定义 swagger 文件而不是自动生成的文件 [英] How to make swagger use custom swagger file instead of auto-generated file in .net core web api

查看:47
本文介绍了如何让 swagger 在 .net core web api 中使用自定义 swagger 文件而不是自动生成的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建新的 .net core 3.1 Web Api 项目并将 Swashbuckle 配置为使用 swagger.

Created new .net core 3.1 Web Api project and configured Swashbuckle to use swagger.

一切正常,但我需要我的应用程序使用我自己的 swagger 规范文件而不是自动生成的文件(swaggerv1swagger.json)

Everything works fine but I need my application use my own swagger spec file instead of auto-generated file(swaggerv1swagger.json)

我搜索了很多帖子,比如 this 但是他们都没有在这里提供帮助.

I searched many posts like this but none of them help here.

我在项目的根路径中创建了 my-custom-swagger.json 文件(与 .csproj 相同的目录)

I have created my-custom-swagger.json file in root path of project(same directory with .csproj)

Startup.cs

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseStaticFiles();
        app.UseSwagger();

    //    app.UseStaticFiles(new StaticFileOptions
    //{
    //    FileProvider = new PhysicalFileProvider(AppContext.BaseDirectory),
    //    RequestPath = "my-custom-swagger.json"
    //    });

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core Test SW");
            c.RoutePrefix = string.Empty;
        });

如何让 swagger 使用 my-custom-swagger.json 文件而不是自动生成的文件

How can I make swagger use my-custom-swagger.json file instead of auto-generated file

推荐答案

如果您想为 swaggerUI 提供您自己的自定义 swagger/OpenAPI 文件,那么您需要执行以下操作(c# .net5 中的代码)

If you want to provide your own custom swagger/OpenAPI file for the swaggerUI, then here's what you need to do (code in c# .net5)

在 ConfigureServices() 添加

In ConfigureServices() add

   .AddSwaggerGen()

.AddSwaggerGenNewtonsoftSupport() 如果你依赖 Newtonsoft.Json 序列化

and .AddSwaggerGenNewtonsoftSupport() if you depend on Newtonsoft.Json serialization

在配置中添加

    .UseSwagger()
    .UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/internal/swagger.json", "v1");
    })

现在我们需要使用自定义文件公开一个端点.

Now we need to expose an endpoint with our custom file.

    .UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/internal/swagger.json", async context =>
        {
            await context.Response.WriteAsync(await File.ReadAllTextAsync("my-custom-swagger.json"));
        });
            
        // the rest of your code goes here
    });

这篇关于如何让 swagger 在 .net core web api 中使用自定义 swagger 文件而不是自动生成的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆