Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger not working (rather exception is thrown) after migrating project from .net core 2.2 to 3.0 preview-7

I have just migrated my project from .net core 2.2 to 3.0 preview 7. I am using Swashbuckle.AspNetCore (v4.0.1) in it. This is my startup class.

public class Startup
    {
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)
        {

            services.AddDbContext<ApplicationDbContext>(options =>
                                                            options.UseSqlServer(
                                                            Configuration["ConnectionStrings:ConnectionStringAzureSQL"]));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);


            services.AddApplicationInsightsTelemetry();

            services.AddLocalization(options => options.ResourcesPath = @"Resources");

            services.AddMemoryCache();

            services.Configure<RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new List<CultureInfo>
                    {
                        new CultureInfo("en-US")
                    };

                options.DefaultRequestCulture = new RequestCulture("en-US");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
            });

            services.AddSwaggerGen(c =>
            {

                c.SwaggerDoc("v1", new Info { Title = "GetAJobToday", Description = "GetAJobTodayAPIs" });

                var xmlPath = AppDomain.CurrentDomain.BaseDirectory + @"PlatformAPI.xml";
                c.IncludeXmlComments(xmlPath);

                c.AddSecurityDefinition("Bearer",
                new ApiKeyScheme
                {
                    In = "header",
                    Description = "Please enter token into the field",
                    Name = "Authorization",
                    Type = "apiKey"
                });

                c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                {
                    {"Bearer", new string[] { }},
                });
            });

            services.AddSingleton<ITelemetryInitializer, HttpContextItemsTelemetryInitializer>();


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            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();
            }

            app.UseRouting();

            app.UseMiddleware<ApiLoggingMiddleware>();

            app.UseHttpsRedirection();

            app.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapControllerRoute("default", "{controller=Auth}/{action=RequestVerificationCode}/{id?}");
            });

            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "GetAJobToday");
            });
        }
    }

But it is throwing this exception when I run it:

AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Swashbuckle.AspNetCore.Swagger.ISwaggerProvider Lifetime: Transient ImplementationType: Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator': Failed to compare two elements in the array.) (Error while validating the service descriptor 'ServiceType: Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory Lifetime: Transient ImplementationType: Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryFactory': Failed to compare two elements in the array.)

like image 537
Muhammad Fahad Nadeem Avatar asked Aug 07 '19 11:08

Muhammad Fahad Nadeem


People also ask

How to create Swagger in ASP NET Core?

In this article, you will learn about swagger in .NET Core. Open Visual Studio and select “Create new project. Select ASP.Net Core Web Application from the templates displayed.

What is swaggergen and swaggerui?

Swashbuckle.SwaggerGen : It provides the functionality to generate JSON Swagger. Swashbuckle.SwaggerUI : The Swagger UI tool uses the above documents for a rich customization for describing the Web API functionality. There are 2 ways that you can install packages.

Is it possible to use swagger with reporting tools?

By the way, Swagger doesn't work! I commented it out! To be able use our Reporting tools in projects that use Swagger, it is necessary to override the controllers used by our reporting components by your own implementations and hide these controllers from Swagger by using the ApiExplorerSettings attribute.

How to get Swagger JSON from Swagger UI?

Now run your application and the Swagger UI can be found at http://localhost:<port>/swagger as images attached. The above added content we can get here in Swagger UI. We can get the swagger json in this place. In case of xml documentation we need enable XML comments.


1 Answers

Upgrading Swashbuckle.AspNetCore and Swashbuckle.AspNetCore.Filters to v 5.0.0-rc2 solved the problem.

like image 113
Muhammad Fahad Nadeem Avatar answered Sep 30 '22 20:09

Muhammad Fahad Nadeem