Sampat
Sampat

Reputation: 116

Swagger UI Not Loading

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

Upvotes: 6

Views: 72545

Answers (9)

Abdul Rehman Sayed
Abdul Rehman Sayed

Reputation: 6672

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
}

Upvotes: 0

Seyedraouf Modarresi
Seyedraouf Modarresi

Reputation: 1297

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

Upvotes: 0

Dev
Dev

Reputation: 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

Upvotes: -1

Agasi Mkhitaryan
Agasi Mkhitaryan

Reputation: 180

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
});

Upvotes: 0

Safyan Yaqoob
Safyan Yaqoob

Reputation: 552

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://stackoverflow.com/a/50629590/9705947

Upvotes: 3

Felix
Felix

Reputation: 31

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.

Upvotes: 3

Jayoti Parkash
Jayoti Parkash

Reputation: 878

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.

Upvotes: 3

Antoine Griffard
Antoine Griffard

Reputation: 103

Did you enable StaticFiles in your startup?

app.UseStaticFiles();

Upvotes: 1

Gurpreet_Carmel_5
Gurpreet_Carmel_5

Reputation: 357

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.

Upvotes: 5

Related Questions