我不建议你这样做,你只会让你的工作更难。
而是使用 ASP.NET Core 为您提供的:环境特定配置。为此,您需要运行两个不同的应用程序,但设置仍然可以在同一个项目中,您只需更改环境变量。
为此,您首先需要一个带有设置的launchSettings.json。
文档中的示例
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:40088/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNET_ENV": "Development"
}
},
"web": {
"commandName": "web",
"environmentVariables": {
"Hosting:Environment": "Staging"
}
}
}
}
这里的环境设置为“暂存”。接下来,您需要为其定义配置。
using Microsoft.AspNet.Builder;
namespace Environments
{
public class StartupStaging
{
public void Configure(IApplicationBuilder app)
{
app.UseWelcomePage();
}
}
}
namespace Environments
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseWelcomePage();
}
}
}
现在,当您的环境设置为 Production 时,将调用 Startup 类(或 StartupProduction,如果存在)。如果您的环境变量设置为Staging,则将调用StartupStaging。
至于不同的 url... 在您的生产应用程序中,您将其设置为
"iisExpress": {
"applicationUrl": "http://example.com/",
"sslPort": 0
}
和你的测试环境
"iisExpress": {
"applicationUrl": "http://example.com/Test/",
"sslPort": 0
}
代码/配置片段取自ASP.NET Core Docs。或者只是将hosting.json 用于不同的环境。
hosting.json
{
"server": "Microsoft.AspNet.Server.Kestrel",
"server.urls": "http://example.com/"
}
在我的脑海中,我认为您还可以拥有多个名为 hosting.production.json 等的文件。