Base solution for your next web application
Open Closed

Swagger UI error 500 #5865


User avatar
0
Ricavir created

Hi,

I'm getting an error when trying to navigate to swagger ui. ASP.NET CORE + angular 6 + v5.5.1

I'm getting follwing error :

INFO  2018-10-30 08:07:44,843 [74   ] soft.AspNetCore.Hosting.Internal.WebHost - Request starting HTTP/1.1 GET http://app.com/swagger/index.html  
ERROR 2018-10-30 08:07:45,262 [74   ] Microsoft.AspNetCore.Server.Kestrel      - Connection id "0HLHTUK2KI941", Request id "0HLHTUK2KI941:00000002": An unhandled exception was thrown by the application.
System.ArgumentNullException: Value cannot be null.
Parameter name: stream
   at System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean leaveOpen)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIIndexMiddleware.RespondWithIndexHtml(HttpResponse response)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIIndexMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at ELEVEN_SOFT.App.Web.Startup.Startup.<>c.<<Configure>b__5_1>d.MoveNext() in C:\repos\App_AspnetZero2\aspnet-core\src\ELEVEN_SOFT.App.Web.Host\Startup\Startup.cs:line 168
--- End of stack trace from previous location where exception was thrown ---
   at Abp.AspNetZeroCore.Web.Authentication.JwtBearer.JwtTokenMiddleware.<>c__DisplayClass0_0.<<UseJwtTokenMiddleware>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context)
   at Abp.AspNetCore.Security.AbpSecurityHeadersMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
 

Error is on startup.cs... App is hoted on Azure.

Any idea how to fix that ?


15 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @ricavir

    Have you configured appsettings.production.json file correctly ? The error seems to be pointing a missing configuration file.

  • User Avatar
    0
    Ricavir created

    I've configured it and don't know if something missing for swagger... Here is the file (i've replaced sensitive data) :

    {
      "ConnectionStrings": {
        "Default": "Server=tcp:...."
      },
      "AbpZeroLicenseCode": "....",
      "Abp": {
        "RedisCache": {
          "ConnectionString": "localhost",
          "DatabaseId": -1
        }
      },
      "App": {
        "ServerRootAddress": "https://{TENANCY_NAME}.app.com/",
        "ClientRootAddress": "https://{TENANCY_NAME}.app.com/",
        "CorsOrigins": "https://app.com,https://app.com",
        "DemoMode": "false",
    	"BackgroudWorkersEnabled": "true"
      },
      "Authentication": {
        "Facebook": {
          "IsEnabled": "false",
          "AppId": "",
          "AppSecret": ""
        },
        "Google": {
          "IsEnabled": "false",
          "ClientId": "",
          "ClientSecret": ""
        },
        "Microsoft": {
          "IsEnabled": "false",
          "ConsumerKey": "",
          "ConsumerSecret": ""
        },
        "JwtBearer": {
          "IsEnabled": "true",
          "SecurityKey": "App_8CFB2E",
          "Issuer": "App",
          "Audience": "App"
        }
      },
      "Recaptcha": {
        "SiteKey": "...",
        "SecretKey": "..."
      },
      "IdentityServer": {
        "IsEnabled": "false",
        "Clients": [
          {
            "ClientId": "client",
            "AllowedGrantTypes": [ "password" ],
            "ClientSecrets": [
              {
                "Value": "...."
              }
            ],
            "AllowedScopes": [ "default-api" ]
          }
        ]
      },
    
      "Payment": {
        "PayPal": {
          "Environment": "sandbox",
          "BaseUrl": "https://api.sandbox.paypal.com/v1",
          "ClientId": "...",
          "ClientSecret": "...",
          "DemoUsername": "...",
          "DemoPassword": "..."
        }
      },
      "Azure": {
        "Storage": {
          "AccountName": "appstorage",
          "AccountKey": "..."
        }
      },
      "GoogleApiV3": {
        "ClientId": "apps.googleusercontent.com",
        "ClientSecret": "...",
        "ApplicationName": "App"
      }
    }
    
  • User Avatar
    0
    ryancyq created
    Support Team

    Hi, can you share swagger related code and any static files related setup in your startup.cs?

  • User Avatar
    0
    Ricavir created

    Hi, I don't change any swagger code (same as zero). No change also to startup (same as zero).

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @ricavir,

    You need to add below config to your appsettings.json right after JwtBearer.

    "OpenId": { "IsEnabled": "false", "Authority": "", "ClientId": "", "ClientSecret": "" }

  • User Avatar
    0
    ismcagdas created
    Support Team

    Please reopen if you haven't solved this problem.

  • User Avatar
    0
    Ricavir created

    Hi @ismcagdas,

    I've added the config you mention after JwtBearer but I still have the same issue. Can you propose a fix please ?

    ERROR 2019-01-29 11:35:18,620 [24   ] Microsoft.AspNetCore.Server.Kestrel      - Connection id "0HLK580R1", Request id "0HLK580R1:00000002": An unhandled exception was thrown by the application.
    System.ArgumentNullException: Value cannot be null.
    Parameter name: stream
       at System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean leaveOpen)
       at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIIndexMiddleware.RespondWithIndexHtml(HttpResponse response)
       at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIIndexMiddleware.Invoke(HttpContext httpContext)
       at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
       at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
       at ELEVEN_SOFT.Logisav.Web.Startup.Startup.<>c.<<Configure>b__5_1>d.MoveNext() in C:\Users\Ricardo Lopes\source\repos\Logisav_AspnetZero2\aspnet-core\src\ELEVEN_SOFT.Logisav.Web.Host\Startup\Startup.cs:line 168
    --- End of stack trace from previous location where exception was thrown ---
       at Abp.AspNetZeroCore.Web.Authentication.JwtBearer.JwtTokenMiddleware.<>c__DisplayClass0_0.<<UseJwtTokenMiddleware>b__0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
       at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context)
       at Abp.AspNetCore.Security.AbpSecurityHeadersMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.Invoke(HttpContext httpContext)
       at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
    
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @ricavir,

    I have two questions;

    1. Could you share your Startup.cs ?
    2. Do you have appsettings.Production.json in your published website root folder ?

    Thanks,

  • User Avatar
    0
    Ricavir created

    Hi,

    1. startup code just bellow
    2. Yes I have appsettings.production.json on root folder
    using System.IO;
    using System;
    using System.Linq;
    using System.Reflection;
    using Abp.AspNetCore;
    using Abp.AspNetCore.SignalR.Hubs;
    using Abp.AspNetZeroCore.Web.Authentication.JwtBearer;
    using Abp.Castle.Logging.Log4Net;
    using Abp.Dependency;
    using Abp.Extensions;
    using Abp.PlugIns;
    using Abp.Timing;
    using Castle.Facilities.Logging;
    using Hangfire;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Cors.Internal;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using ELEVEN_SOFT.Myapp.Configuration;
    using ELEVEN_SOFT.Myapp.EntityFrameworkCore;
    using ELEVEN_SOFT.Myapp.Identity;
    using ELEVEN_SOFT.Myapp.Web.Chat.SignalR;
    using PaulMiami.AspNetCore.Mvc.Recaptcha;
    using Swashbuckle.AspNetCore.Swagger;
    using ELEVEN_SOFT.Myapp.Web.IdentityServer;
    using ILoggerFactory = Microsoft.Extensions.Logging.ILoggerFactory;
    
    namespace ELEVEN_SOFT.Myapp.Web.Startup
    {
        public class Startup
        {
            private const string DefaultCorsPolicyName = "localhost";
    
            private readonly IConfigurationRoot _appConfiguration;
            private readonly IHostingEnvironment _hostingEnvironment;
    
            public Startup(IHostingEnvironment env)
            {
                _hostingEnvironment = env;
                _appConfiguration = env.GetAppConfiguration();
            }
    
            public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                //MVC
                services.AddMvc(options =>
                {
                    options.Filters.Add(new CorsAuthorizationFilterFactory(DefaultCorsPolicyName));
                }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); ;
    
                services.AddSignalR(options => { options.EnableDetailedErrors = true; });
    
                //Configure CORS for angular2 UI
                services.AddCors(options =>
                {
                    options.AddPolicy(DefaultCorsPolicyName, builder =>
                    {
                        //App:CorsOrigins in appsettings.json can contain more than one address with splitted by comma.
                        builder
                            .WithOrigins(
                                // App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
                                _appConfiguration["App:CorsOrigins"]
                                    .Split(",", StringSplitOptions.RemoveEmptyEntries)
                                    .Select(o => o.RemovePostFix("/"))
                                    .ToArray()
                            )
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials();
                    });
                });
    
                IdentityRegistrar.Register(services);
                AuthConfigurer.Configure(services, _appConfiguration);
    
                //Identity server
                if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"]))
                {
                    IdentityServerRegistrar.Register(services, _appConfiguration);
                }
    
                //Swagger - Enable this line and the related lines in Configure method to enable swagger UI
                services.AddSwaggerGen(options =>
                {
                    options.SwaggerDoc("v1", new Info { Title = "Myapp API", Version = "v1" });
                    options.DocInclusionPredicate((docName, description) => true);
    
                    //Note: This is just for showing Authorize button on the UI. 
                    //Authorize button's behaviour is handled in wwwroot/swagger/ui/index.html
                    options.AddSecurityDefinition("Bearer", new BasicAuthScheme());
                });
    
                //Recaptcha
                services.AddRecaptcha(new RecaptchaOptions
                {
                    SiteKey = _appConfiguration["Recaptcha:SiteKey"],
                    SecretKey = _appConfiguration["Recaptcha:SecretKey"]
                });
    
                //Hangfire (Enable to use Hangfire instead of default job manager)
                //services.AddHangfire(config =>
                //{
                //    config.UseSqlServerStorage(_appConfiguration.GetConnectionString("Default"));
                //});
    
                //Configure Abp and Dependency Injection
                return services.AddAbp<MyappWebHostModule>(options =>
                {
                    //Configure Log4Net logging
                    options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                        f => f.UseAbpLog4Net().WithConfig("log4net.config")
                    );
    
                    options.PlugInSources.AddFolder(Path.Combine(_hostingEnvironment.WebRootPath, "Plugins"), SearchOption.AllDirectories);
                });
            }
    
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                //Initializes ABP framework.
                app.UseAbp(options =>
                {
                    options.UseAbpRequestLocalization = false; //used below: UseAbpRequestLocalization
                });
    
                Clock.Provider = ClockProviders.Utc;
    
                app.UseCors(DefaultCorsPolicyName); //Enable CORS!
    
                app.UseAuthentication();
                app.UseJwtTokenMiddleware();
    
                if (bool.Parse(_appConfiguration["IdentityServer:IsEnabled"]))
                {
                    app.UseJwtTokenMiddleware("IdentityBearer");
                    app.UseIdentityServer();
                }
    
                app.Use(async (context, next) =>
                {
                    await next();
                    if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
                    {
                        context.Request.Path = "/index.html";
                        await next();
                    }
                });
                app.UseStaticFiles();
    
                using (var scope = app.ApplicationServices.CreateScope())
                {
                    if (scope.ServiceProvider.GetService<DatabaseCheckHelper>().Exist(_appConfiguration["ConnectionStrings:Default"]))
                    {
                        app.UseAbpRequestLocalization();
                    }
                }
    
                app.UseSignalR(routes =>
                {
                    routes.MapHub<AbpCommonHub>("/signalr");
                    routes.MapHub<ChatHub>("/signalr-chat");
                });
    
                //Hangfire dashboard & server (Enable to use Hangfire instead of default job manager)
                //app.UseHangfireDashboard("/hangfire", new DashboardOptions
                //{
                //    Authorization = new[] { new AbpHangfireAuthorizationFilter(AppPermissions.Pages_Administration_HangfireDashboard)  }
                //});
                //app.UseHangfireServer();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "defaultWithArea",
                        template: "{area}/{controller=Home}/{action=Index}/{id?}");
    
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
    
                // Enable middleware to serve generated Swagger as a JSON endpoint
                app.UseSwagger();
                // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
    
                app.UseSwaggerUI(options =>
                {
                    options.SwaggerEndpoint("/swagger/v1/swagger.json", "Myapp API V1");
                    options.IndexStream = () => Assembly.GetExecutingAssembly()
                        .GetManifestResourceStream("ELEVEN_SOFT.Myapp.Web.wwwroot.swagger.ui.index.html");
                }); //URL: /swagger
            }
        }
    }
    
  • User Avatar
    0
    maliming created
    Support Team

    I think your problem is in

    options.IndexStream = () => Assembly.GetExecutingAssembly() .GetManifestResourceStream("ELEVEN_SOFT.Myapp.Web.wwwroot.swagger.ui.index.html");

    Please check: var names = Assembly.GetExecutingAssembly().GetManifestResourceNames().ToList();

    see:https://github.com/aspnetboilerplate/module-zero-core-template/issues/233#issuecomment-389168846

  • User Avatar
    0
    Ricavir created

    I removed line

    options.IndexStream = () => Assembly.GetExecutingAssembly() .GetManifestResourceStream("ELEVEN_SOFT.Myapp.Web.wwwroot.swagger.ui.index.html");

    this makes swagger UI working again but I can't autenticate (tenant input is missing).

    I've tried to change .GetManifestResourceStream("ELEVEN_SOFT.Myapp.Web.wwwroot.swagger.ui.index.html"); by .GetManifestResourceStream("ELEVEN_SOFT.Myapp.Web.Host.wwwroot.swagger.ui.index.html"); But I'm having same issue.

    I've checked var names = Assembly.GetExecutingAssembly().GetManifestResourceNames().ToList(); : this returns no elements at all.

    Any suggestion ?

  • User Avatar
    0
    maliming created
    Support Team

    Add the following content to your project's csproj file.

    <ItemGroup>
        <Content Remove="wwwroot\swagger\ui\index.html" />
     </ItemGroup>
    
  • User Avatar
    0
    Ricavir created

    this code is already there

  • User Avatar
    0
    maliming created
    Support Team

    Sorry, I copied it incorrectly. Does the following code exist?

    <ItemGroup>
         <EmbeddedResource Include="wwwroot\swagger\ui\index.html">
           <CopyToOutputDirectory>Always</CopyToOutputDirectory>
         </EmbeddedResource>
       </ItemGroup>
    
  • User Avatar
    0
    Ricavir created

    It's working now ! Thank you @maliming