提问者:小点点

Cutomize SwaggerUIASP.NET核心WebAPI


我正在尝试在我的ASP.NET核心网络API上自定义招摇UI。

我想要这样的UI:

我遵循这些教程:

  • https://learn.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio
  • https://github.com/swagger-api/swagger-ui

这是Startup. cs配置:

// Add the detail information for the API.
services.ConfigureSwaggerGen(options =>
{
    // Determine base path for the application.
    var basePath = _env.WebRootPath;

    // Complete path
    var xmlPath = Path.Combine(basePath, "myapi.xml");

    // Set the comments path for the swagger json and ui.
    options.IncludeXmlComments(xmlPath);
});

app.UseStaticFiles();

// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();

// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUI(c =>
{                
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI");
});  

我已经从git存储库下载了swagger用户界面文件,并像这样放在我的项目上:

我不知道这是否是正确的做法,但我看不出大摇大摆UI有任何变化。


共3个答案

匿名用户

您正在使用的教程是:Swashuckle. AspNetCore不幸的是,在那个项目中,他们仍然使用Swagger-UI版本2.x,您的屏幕截图显示的是版本3.x


有一些拉取请求更新到最新的Swagger-UI:

  • https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/453
  • https://github.com/domaindrivendev/Swashbuckle.AspNetCore/pull/543

但不幸的是,在合并这些方面没有太大进展。

我看到你知道如何从git存储库下载文件…
我的建议:
不要下载swagger-用户界面文件,而是从使用您需要的版本(例如:alexvalyskiy/Swashuckle. AspNetCore)的分叉下载整个项目Swashuckle.AspNetCore,然后在您的项目中添加对该项目的引用而不是nuget包。


另一种选择可能是创建您自己的Swashuckle. AspNetCore分支合并您需要的修复,然后使用不同的名称发布您自己的Nuget包。

匿名用户

//I hope this will help you , you can get //https://localhost:44x22/docs/index.html

        app.UseSwagger(o =>
        {
            o.RouteTemplate = "docs/{documentName}/docs.json";
        });
        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
        // specifying the Swagger JSON endpoint.
        //This line enables Swagger UI, which provides us with a nice, simple UI with which we can view our API calls.
        app.UseSwaggerUI(c =>
        {

            c.IndexStream = () => GetType().Assembly
   .GetManifestResourceStream("CustomUIIndex.Swagger.index.html"); // requires file to be added as an embedded resource
            c.InjectStylesheet("/css/swagger-ui/custom.css");// css path
            c.InjectJavascript("../css/swagger-ui/custom.js"); javascript path
            c.RoutePrefix = "docs";
            c.SwaggerEndpoint("../docs/v1/docs.json", "API v1");
            c.SwaggerEndpoint("../docs/v2/docs.json", "API V2");
        });
        app.UseStaticFiles();

匿名用户

我遇到了类似的问题,我需要注入我的样式工作表:

c.InjectStylesheet("/Swagger/Ui/custom.css")

这已添加到Startup. cs文件中的app.UseSwaggerUI

以下文章有所帮助,但我必须合并两者的信息才能找到答案:

  • https://cpratt.co/customizing-swagger-ui-in-asp-net-core/
  • https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.1