.NET 5 + Custom appsettings.json - The SPA default page middleware could not return the default page

Viewed 481

I have a C# .NET5 Project with ReactJS (VS Project Template for C# projects).

If I do not change appsettings.json and launchSettings.json everything works fine (localhost DEV and also TEST server where I send app by Publish).

In ASP.NET MVC5 (.NET Framework) I use Publish button and after switch Debug or Release I had web.config with the same suffix as web.Release.config, and in this file I had configuration for Release DB.

Now in .NET 5 I would like to have more appsettings file with diff configuration (Home, Work, Contractor, Test, Prod), for only switch config name (Run Name in VS) which is defined and connected with launchSettings.json, now I must on diff PC comment ConnectionString for selected DB on machine

And I like to have also for Publish button in main runnable project load only appsettings.Prod.json to Production server

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

        Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();

        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseSerilog()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

appsettings.json

{
  "Serilog": {
    "Using": [],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "Logs\\AuditInfo-.log",
          "rollingInterval": "Day", // Rolling Interval
          "outputTemplate": "{Timestamp:dd.MM.yyyy HH:mm:ss} [{Level}] ({ThreadId}) - {Message}{NewLine}{Exception}"
        }
      }
    ]

  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=home;Initial Catalog=test;Integrated Security=True;"
    //"DefaultConnection": "Data Source=test;Initial Catalog=test;Integrated Security=True;"
    //"DefaultConnection": "Data Source=work;Initial Catalog=test;Integrated Security=True;"
    //"DefaultConnection": "Data Source=contractor;Initial Catalog=test;Integrated Security=True;"
  }
}

appsettings.Development.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:53806",
      "sslPort": 44348
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Search": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

I have these appsettings.___.json file by default

enter image description here

If I add new appsettings.Dev.json and edit launchSettings.json like:

launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:53806",
      "sslPort": 44348
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Dev": { // NEW RUN option with connect to Dev appsettings file
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Dev"
      }
    },
    "Test": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

appsettings.Dev.json

{
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=dev;Initial Catalog=dev;Integrated Security=True;"
  }
}

I got only HTTP 500 Response and in log I got this error:

02.04.2021 19:27:57 [Error] (6) - An unhandled exception has occurred while executing the request.
System.InvalidOperationException: The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request.

   at Microsoft.AspNetCore.SpaServices.SpaDefaultPageMiddleware.<>c__DisplayClass0_0.<Attach>b__1(HttpContext context, Func`1 next)
   at Microsoft.AspNetCore.Builder.UseExtensions.<>c__DisplayClass0_1.<Use>b__1(HttpContext context)
   at Microsoft.AspNetCore.Builder.UseExtensions.<>c__DisplayClass0_2.<Use>b__2()
   at Microsoft.AspNetCore.SpaServices.SpaDefaultPageMiddleware.<>c__DisplayClass0_0.<Attach>b__0(HttpContext context, Func`1 next)
   at Microsoft.AspNetCore.Builder.UseExtensions.<>c__DisplayClass0_1.<Use>b__1(HttpContext context)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
   at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)

The main problem is in Startup.cs in env.IsDevelopment() if I comment condition, everything works fine (for Dev I use IISExpress):

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";

            //if (env.IsDevelopment())
            //{
                spa.UseReactDevelopmentServer(npmScript: "start");
            //}
        });

Is it possible to register another ASPNETCORE_ENVIRONMENT variable then Development and Use it with function env.IsDevelopment() ? Or is there another way how to do it ?

1 Answers
Related