在 .NET Core 的 Swagger / Swashbuckle 中使用自定义 Index.Html 时出现问题

2024-02-02

我在使用自定义 index.html 和其他资产与 swashbuckle 时遇到困难。 Swashbuckle/Swagger 似乎根本不认识或使用它们。我确实设置了 app.UseDefaultFiles() 和 app.UseStaticFiles() 。我试图理解我做错了什么。

我尝试设置与 Microsoft 文章中定义的配置有些相似的配置,但没有成功。 (https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio)

我目前正在使用文章中引用的 dist 文件夹中的文件(https://github.com/swagger-api/swagger-ui/tree/2.x/dist https://github.com/swagger-api/swagger-ui/tree/2.x/dist)以及提供的自定义 css 文件。

我的index.html文件位于/wwwroot/swagger/ui下 自定义 css 文件位于 /wwwroot/swagger/ui/css 下(如 custom.css)

这是我的 Startup.cs 类。

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
             .AddJsonOptions(options =>
             {
                 // Swagger - Format JSON
                 options.SerializerSettings.Formatting = Formatting.Indented;
             });

        // Register the Swagger generator, defining one or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.DescribeAllEnumsAsStrings();
            c.DescribeStringEnumsInCamelCase();
            // c.DescribeAllParametersInCamelCase();                

            c.SwaggerDoc("v1",
                new Info
                {
                    Title = "My Web API - v1",
                    Version = "v1",
                    Description = "New and improved version. A simple example ASP.NET Core Web API. "

                }
            );

            c.SwaggerDoc("v2",
                new Info
                {
                    Title = "My Web API - v2",
                    Version = "v2",
                    Description = "New and improved version. A simple example ASP.NET Core Web API. "
                }
            );

            // Set the comments path for the Swagger JSON and UI.
            var basePath = AppContext.BaseDirectory;
            var xmlPath = Path.Combine(basePath, "ApiTest.xml");
            c.IncludeXmlComments(xmlPath);
        });

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        string swaggerUIFilesPath = env.WebRootPath + "\\swagger\\ui";

        if (!string.IsNullOrEmpty(swaggerUIFilesPath))
        {
            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(swaggerUIFilesPath),
                RequestPath = new PathString("/api-docs"),
            });
        }

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger(c =>
        {
            c.RouteTemplate = "api-docs/{documentName}/swagger.json";
        });

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            //c.ShowJsonEditor();
            c.RoutePrefix = "api-docs";
            c.SwaggerEndpoint("/api-docs/v1/swagger.json", "My Web API - V1 ");
            c.SwaggerEndpoint("/api-docs/v2/swagger.json", "My Web API - V2 ");
            c.DocumentTitle("My Web API");
        });

        app.UseMvc();
    }
}

我的最终目标是能够使用类似此处提供的石板风格主题(https://github.com/omnifone/slate-swagger-ui https://github.com/omnifone/slate-swagger-ui)。目前,我只是尝试让 Swashbuckle/Swagger 使用 Microsoft 文档中引用的自定义文件,然后再尝试使其他文件正常工作。

我真的不想尝试将我的资产转换为嵌入式资源——因为会有很多这样的资源。我只想引用普通的index.html 文件并能够使用其所有引用的文件。

我究竟做错了什么?

相关软件版本

  • .Net核心版本:2.0.3
  • Swashbuckle.AspNetCore:1.2.0
  • Windows 10 企业版 1703
  • Visual Studio 2017 企业版 15.5.2

以下是我发现在 .NET Core 项目中替换 SwashBuckle 的 index.html 所需的最少操作:

  • 从这里获取原始index.html的副本:https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.SwaggerUI/index.html https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.SwaggerUI/index.html

  • 将该副本放在项目的某个子文件夹中。
    该文件可能有不同的名称,我选择:\Resources\Swagger_Custom_index.html

  • 在解决方案资源管理器中右键单击该文件,选择“属性”,然后在左侧窗格中选择“配置属性”。在右侧窗格的“高级”下,找到条目“构建操作”并将其设置为“嵌入资源”。单击“确定”。

  • 在 Startup.cs 中将以下行添加到您的app.UseSwaggerUI() call:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //...
    
        app.UseSwaggerUI(c =>
        {
            c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Your.Default.Namespace.Resources.Swagger_Custom_index.html");
        });
    
        //...
    }
    
  • 上面的文件资源的标识符GetManifestResourceStream方法由以下部分组成:

    1. 您的默认命名空间(即“Your.Default.Namespace”)
    2. 资源的子路径(即“资源”)
    3. 您的资源的文件名(即“Swagger_Custom_index.html”)

    所有三个部分都使用点连接(此处没有斜杠或反斜杠)。
    如果您不使用子路径但将资源放在根目录中,则只需省略第 2 部分。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 .NET Core 的 Swagger / Swashbuckle 中使用自定义 Index.Html 时出现问题 的相关文章

随机推荐