Swagger UI Not Loading
Asked Answered
T

9

6

Swagger UI is not loading, Json is loading as expected but issue exists with supported js, css files.

you can see the issues in this images

Towland answered 9/1, 2019 at 10:23 Comment(2)
Could you add the code where you are adding Swagger UI to your app?Jeramie
Just figured it out , i have wrote " c.RoutePrefix = string.Empty; " under configure.... so i need to access like : localhost:<port> -- then Swagger is loading, /swagger is not required. Thanks for your help :)Towland
O
5

Try to copy the /dist directory in vendor/swagger-api/swagger-ui inside your project. I'm not sure about the proper way, but I was facing the same issue and it worked for me. Also, try to provide more details of the issue you are facing, maybe code snippets too. Alternatively, try the following :

  1. Check if all your controller methods have [http] tag. If they all do and still doesn't work go to step 2
  2. In your configure function to ensure that you have app.UseStaticFiles(); If it still doesn't work go to step 3
  3. Uninstall and reinstall swagger. If it doesn't work go to step 4 (Core Only)
  4. If you are using Core Install Microsoft.AspNetCore.StaticFiles and reference it in your project.
Obelia answered 9/1, 2019 at 10:32 Comment(0)
T
3

The reason behind this issue you need to follow the below-mentioned steps:

  1. Under Startup.cs file there is a method "ConfigureServices" in this do the following:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
        // Configure database connection
        services.Configure<Settings>(options =>
        {
            options.ConnectionString = Configuration.GetSection("database:ConnectionString").Value;
            options.Database = Configuration.GetSection("Db:Database").Value;
        });
    
        //register the RecordedMediaContext dependency here
        services.AddTransient<ITestService, TestService>();
        // Register the Swagger generator, defining 1 or more Swagger documents
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    
            // Set the comments path for the Swagger JSON and UI.
            var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
            c.IncludeXmlComments(xmlPath);
        });
    
        // Max file upload sixe 5gb =5,368,709,120 bytes
        services.Configure<FormOptions>(x => x.MultipartBodyLengthLimit = 5368709120);
    }
    
  2. Then under Configure method under the same Startup.cs file add the following code

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        string baseApiUrl = Configuration.GetSection("BaseApiUrl").Value;
        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();
    
        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            #if DEBUG
                // For Debug in Kestrel
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API V1");
            #else
                // To deploy on IIS
                c.SwaggerEndpoint(""+baseApiUrl+"/swagger/v1/swagger.json", "My API V1");
            #endif
        });
    
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
    
        //Accept All HTTP Request Methods from all origins
        //app.UseCors(builder => builder.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
    
        app.UseHttpsRedirection();
        #if !DEBUG
            app.UseDefaultFiles();
            app.UseStaticFiles();
        #endif
        app.UseMvc();
    }
    

    Thanks.

Tailwind answered 9/1, 2019 at 10:38 Comment(5)
What's BaseApiUrl?Lamasery
BaseApiUrl will be the domain name like if you are debugging the application then it uses localhost:portnumber//swagger/index.html and if hosted somewhere then its domain name. like baseApiUrl= localhost:port numberTailwind
Why do you need to add that? Swagger should bind to what ever it's listening on and your reverse proxy should just pass the request to the API and return the response.Lamasery
Yes, you are right and it's not working while I deployed it on IIS. I tried it both ways, and it starts working in this way.Tailwind
No Luck still required Css, JS files are not loadingTowland
D
3

I faced same issue: Swagger works just fine locally, but doesn't show UI once published to IIS. The problem was resolved by adding .js and .json files as allowed to Request Filtering feature of IIS. These files are not listed there by default for newly created web sites.

Decrial answered 3/2, 2020 at 10:56 Comment(0)
G
3

Try to remove the .vs folder visual studio will automatically create it again when building the project. Swagger Page working after deleting it.

According to Tyler Findlay answer. https://mcmap.net/q/968437/-swagger-page-is-404-not-found-in-mvc-net-core

Geller answered 13/12, 2020 at 17:32 Comment(0)
C
1

Did you enable StaticFiles in your startup?

app.UseStaticFiles();
Cologarithm answered 9/1, 2019 at 13:37 Comment(1)
already added, but no luck. it is not able to load the required JS, Css for swagger UI.Towland
B
0

I was following the original guide on msdoc trying to enable swagger support and after adding this block with the RoutePrefix I didn't realize the path changed from http://localhost:<port>/swagger to http://localhost:<port>, thanks to the Sampat for pointing it out.

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    c.RoutePrefix = string.Empty; // this changes the default path
});
Brougham answered 7/2, 2021 at 20:3 Comment(0)
S
0

I had the same problem and the problem has been by doing the following steps.

Click on the Request Filtering

enter image description here

Right-click on the newly opened window. and click on the Allow File Name Extention.

enter image description here

Then after adding .js, .json, and .css file extensions.

Finally new file extensions must be as follow.

enter image description here

Selfhood answered 11/11, 2022 at 13:50 Comment(0)
F
0

I had a base class from which all my controllers inherited. I had created a public method in this base class which did not have [httpget] or [httpost] which was causing the swagger to fail.

Since I did not want this method exposed outside via API, I had to add [ApiExplorerSettings(IgnoreApi = true)] setting on the method.

[ApiExplorerSettings(IgnoreApi = true)]
public void SomeMethod(string strMessage)
{
    //Did somethinf
}
Frosting answered 27/8, 2023 at 11:58 Comment(0)
T
-1
  • List item

/*package com.dynamind.config;

  1. import com.dynamind.constant.DynamindConstant; import org.springframework.beans.factory.annotatioenter code heren.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.env.Environment; import org.springframework.http.ResponseEntity; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.ApiKey; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2;

    import java.time.LocalDate; import java.util.Arrays; import java.util.Collections;

    • List item

    @Configuration @EnableSwagger2 @Profile(value = {"dev","local","uat","beta"}) public class SwaggerConfig {

    @Autowired
    Environment environment;
    
    ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("Dynamind API - " + Arrays.toString(environment.getActiveProfiles()).toUpperCase()).
                description("API Reference").version("1.0.0").build();
    }
    
    @Bean
    public Docket customImplementation() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .securitySchemes(Collections.singletonList(authorizationKey())).select().paths(PathSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.dynamind")).build().pathMapping("/")
                .useDefaultResponseMessages(false).directModelSubstitute(LocalDate.class,
    

    String.class) .genericModelSubstitutes(ResponseEntity.class); }

    private ApiKey authorizationKey() {
        return new ApiKey(DynamindConstant.AUTHORIZATION, DynamindConstant.AUTHORIZATION, "header");
    } }
    

    */

    Try it

Terraterrace answered 22/6, 2022 at 18:10 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Arrester

© 2022 - 2024 — McMap. All rights reserved.