Modifications to Swagger UI header

夙愿已清 提交于 2019-11-29 19:51:23

问题


I have created a personal WEB API using Swashbuckle and Swagger API.

While I am able to integrate this successfully, I would like to modify the default UI for Swagger. Changing the color of the header and replacing the swagger image.

Is this possible by modifying existing files?


回答1:


These are the steps I took:

  1. Create a new file SwaggerHeader.css
  2. Right click on SwaggerHeader.css, select Properties. Set Build action to Embedded Resource.
  3. In SwaggerConfig.cs, add the below line of code:
      EnableSwaggerUi("Document/{*assetPath}", c =>
      {
          c.InjectStylesheet(typeof(SwaggerConfig).Assembly,
          "ProjectName.FolderName.SwaggerHeader.css");
      }
  1. SwaggerHeader.css looks like the below:

/* swagger ui customization */
body.swagger-section #header {
    background-color: white;
    background: url(your-new-logo.png) no-repeat;
    background-position-x: 250px;
    height: 50px;
}

body.swagger-section #header .swagger-ui-wrap #logo {
        display: none;
}



回答2:


To change the color, you can inject a new stylesheet

Qoute from the SwaggerConfig.cs file

Use the "InjectStylesheet" option to enrich the UI with one or more a dditional CSS stylesheets. The file must be included in your project as an "Embedded Resource", and then the resource's "Logical Name" is passed to the method as shown below. c.InjectStylesheet(containingAssembly,"Swashbuckle.Dummy.SwaggerExtensions.testStyles1.css");

Remember to set Build Action of the stylesheet to "Embedded Resource".




回答3:


  1. First step is to add a new css file in your project, with your custom rules. For example :

    .swagger-section #header { background-color: #fadc00; }
    
  2. Right click on the new file and go Properties. In "Build Actions" select "Embedded Ressources".

  3. Inside the SwaggerConfig file, inject the stylesheet. The resource name should be the "Logical Name" for the resource. That is where I got stuck, but thanks to this Swashbuckle doc I could infer the logical name following the rule :

    Default Namespace for your project "dot" folder containing the resource "dot" file name with extension.

It's based on the Project's default namespace, file location and file extension. For example, given a default namespace of "YourWebApiProject" and a file located at "/SwaggerExtensions/index.html", then the resource will be assigned the name - "YourWebApiProject.SwaggerExtensions.index.html"

For example :

.EnableSwaggerUi(c =>
{
    c.InjectStylesheet(thisAssembly, "Some.Default.Namespace.App_Start.swagger.css");
});



回答4:


Alternativelly, I have created a custom.css in my wwwroot folder and just added

options.InjectStylesheet("/custom.css");

and it worked as well.



来源:https://stackoverflow.com/questions/36291146/modifications-to-swagger-ui-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!