14

I updated Our net core API application from 2.1 to 3.1, SwashBuckle.Asp.NetCore to 5.0.0. Here is my startup set:

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)
    {
     string authServerUrl = "http://testserver.com/identityserver4";
         services.AddControllersWithViews();

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "NetCore API V1" });

            // Define the OAuth2.0 scheme that's in use (i.e. Implicit Flow)
            c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
            {
                Type = SecuritySchemeType.OAuth2,
                Flows = new OpenApiOAuthFlows
                {
                    AuthorizationCode = new OpenApiOAuthFlow
                    {
                            AuthorizationUrl = new Uri(authServerUrl + "connect/authorize"),
                            TokenUrl = new Uri(authServerUrl + "connect/token"),
                            Scopes = new Dictionary<string, string>
                            {
                                { "netCoreAPI.read", "read permission" },
                                { "netCoreAPI.write", "write permission" }
                            }                        }
                }
            });

            c.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
                    },
                    new[] { "netCoreAPI.read", "netCoreAPI.write" }
                }
            });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("swagger/v1/swagger.json", "NetCore V1");
                c.EnableDeepLinking();
                c.OAuthClientId("clientId");
                c.OAuthClientSecret("clientSecret");
                c.OAuthAppName("netCoreApp");
                c.OAuthScopeSeparator(" ");
                c.OAuthUsePkce();
            });
        });
    }
}

The initial Swagger UI displays relatively quickly. However, when a method in a controller is clicked, it takes 30 seconds to display "Try it out" button. Is there a way to debug the problem? Or Is there anyone having the same problem? Before the code was converted from SwashBuckle 2.5 and net core 2.1 to SwashBuckle 5.0 and net core 3.1, the swagger UI works very fast.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
user3097695
  • 1,152
  • 2
  • 16
  • 42
  • What's the size of your `swagger.json` file? Does the problematic endpoint use recursive and/or highly nested models? How many lines of JSON are in the displayed request bodies and response bodies? – Helen Jan 21 '20 at 21:20
  • @Helen I don't have swagger.json file. I am using Swagger in C# net Core Api to expose Api methods for Controller. When my application runs, it shows a web pages with all my controllers, and all the api methods for each controller. From there, I can test my api methods. My authorization server is IdentityServer4. – user3097695 Jan 21 '20 at 22:20
  • 1
    See [How to export a Swagger JSON/YAML file from Swagger UI](https://stackoverflow.com/q/48525546/113116). The slowness may be caused by the large file size and/or highly nested data models. – Helen Jan 22 '20 at 07:20
  • I have the same issue. The size of the swagger.json equals approximately 160kb – Calabonga Feb 12 '20 at 10:58

4 Answers4

26

I'm using "Swashbuckle.AspNetCore.SwaggerUI" Version="5.6.3" And with that version switching to "Swashbuckle.AspNetCore.Newtonsoft" was not really helping. There was no significant improvement.

Then I have fount this issue listed on Github. It is an old resolved issue but reopened in 2020. Where they explain Swagger UI 3.x has "Pretty print" and "Syntax highlight" which causing the render issues. It can be turned off in Swagger config:

SwaggerUI({
        syntaxHighlight: {
          activated: false,
          theme: "agate"
        },
        //url: path,
        ....
      });

In .NET Core you can access config as well: Setup.cs in Configure()

app.UseSwagger()
    .UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Web API");
        c.ConfigObject.AdditionalItems.Add("syntaxHighlight", false); //Turns off syntax highlight which causing performance issues...
        c.ConfigObject.AdditionalItems.Add("theme", "agate"); //Reverts Swagger UI 2.x  theme which is simpler not much performance benefit...
    });
Major
  • 5,948
  • 2
  • 45
  • 60
17

Are you using NewtonSoft? You need to add:

Install-Package Swashbuckle.AspNetCore.Newtonsoft -Version 5.1.0

And add:

services.AddSwaggerGenNewtonsoftSupport();
// explicit opt-in - needs to be placed after AddSwaggerGen()

https://github.com/domaindrivendev/Swashbuckle.AspNetCore#systemtextjson-stj-vs-newtonsoft

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Steve Bates
  • 186
  • 1
  • 3
  • After I added above package, it throws exception. System.NullReferenceException: Object reference not set to an instance of an object. at Swashbuckle.AspNetCore.SwaggerGen.MemberInfoExtensions.GetInlineOrMetadataTypeAttributes(MemberInfo memberInfo) at Swashbuckle.AspNetCore.SwaggerGen.SchemaGenerator.GenerateObjectSchema(SerializerMetadata serializerMetadata, SchemaRepository schemaRepository) at – user3097695 Mar 17 '20 at 17:16
  • thanks! The current version 5.3.3 is now also working – user8606929 Apr 24 '20 at 17:51
0

Allowing the binary serialization in csproj speeded it up for me: <EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>

Adi Bilauca
  • 181
  • 2
  • 10
-2

I faced a similar problem with swagger in my .Net 5 Web API project and it was fixed after following the steps and adding the code mentioned in both the above answers. To summarize:

  1. Installed package Swashbuckle.AspNetCore.Newtonsoft 6.1.4
  2. This line was already there in the Startup.cs: services.AddSwaggerGenNewtonsoftSupport();
  3. Added 2 lines of code in the Configure() of Startup.cs: (c.ConfigObject.AdditionalItems...)
NPV
  • 29
  • 2