【问题标题】:.NET 5 + Custom appsettings.json - The SPA default page middleware could not return the default page.NET 5 + 自定义 appsettings.json - SPA 默认页面中间件无法返回默认页面
【发布时间】:2021-04-02 18:11:51
【问题描述】:

我有一个带有 ReactJS 的 C# .NET5 项目(用于 C# 项目的 VS 项目模板)。

如果我不更改 appsettings.jsonlaunchSettings.json 一切正常(本地 DEV 以及我通过发布发送应用程序的测试服务器)。

在 ASP.NET MVC5 (.NET Framework) 中,我使用“发布”按钮,在切换“调试”或“发布”之后,我得到了与 web.Release.config 具有相同后缀的 web.config,并且在这个文件中我有发布 DB 的配置。

现在在 .NET 5 中,我希望有更多具有差异配置(家庭、工作、承包商、测试、生产)的 appsettings 文件,仅用于切换配置名称(在 VS 中运行名称)定义并与 launchSettings.json 连接,现在我必须在 diff PC 上为机器上选定的 DB 注释 ConnectionString

我也喜欢在主可运行项目中的 Publish 按钮仅将 appsettings.Prod.json 加载到生产服务器

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"
      }
    }
  }
}

我默认有这些 appsettings.___.json 文件

如果我添加新的 appsettings.Dev.json 并编辑 launchSettings.json,例如:

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

我只收到了 HTTP 500 响应,在日志中我收到了这个错误

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)

主要问题在 env.IsDevelopment() 中的 Startup.cs 中,如果我评论条件,一切正常(对于 Dev 我使用 IISExpress):

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

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

是否可以注册另一个 ASPNETCORE_ENVIRONMENT 变量然后开发并与函数 env.IsDevelopment() 一起使用?或者还有其他方法可以做到吗?

【问题讨论】:

  • 您的新设置文件是否设置为复制到输出目录?你确认它存在了吗?
  • 是的,所有文件都在构建目录(bin)中,已设置“如果较新则复制”

标签: c# json reactjs .net-5


【解决方案1】:

env.IsDevelopment() 仅在 ASPNETCORE_ENVIRONMENT is Development 时为 true。不过还有其他选择:

  1. 使用env.IsEnvironment('some_env')
  2. 编写您自己的扩展程序 - here is the source for env.IsDevelopment

【讨论】:

    猜你喜欢
    • 2020-09-04
    • 2021-06-17
    • 2021-10-26
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 2020-11-16
    • 1970-01-01
    相关资源
    最近更新 更多