.NET Core 2.2 Razor Pages 基于 Dev 或 Prod 环境的条件连接字符串

.NET Core 2.2 Razor Pages Conditional Connections String based on Dev or Prod Enviroment

多年来我一直在 .NET Web Forms 中这样做:

  Dim conn As New SqlConnection(f1.fUseThisConnection(Server.MachineName))

Public Function fUseThisConnection(ByVal strThisMachine As String) As String

    If strThisMachine = "T61" Then
        fUseThisConnection = ConfigurationManager.AppSettings("DevHome")
    Else
        fUseThisConnection = ConfigurationManager.AppSettings("Production")
    End If

End Function

AppSettings 在 Web.config:

<appSettings>
    <add key="Production" value="server=xxx;uid=xxx;pwd=xxx;database=xxx;pooling=false" />
    <add key="DevHome" value="server=xxx;uid=xxx;pwd=xxx;database=xxx;pooling=false" />

但我还没有搜索并找到适合我的 C# Razor Pages 的任何东西。 Microsoft howto 中的任何内容都让我感到困惑。

这是我的 appSetting.json 在我的 Razor Pages 项目中:

  "ConnectionStrings": {

    "DefaultConnection": "Data Source=Txx\SQLxxx;Initial Catalog=xxx;Persist Security Info=True",
    "Production": "Data Source=xxx;Initial Catalog=xxx;Integrated Security=True;User ID=xxx;Password=xxx"
  },

这里是我引用连接字符串的地方——它是硬编码的——但我希望有一种方法可以执行 "If" 语句:"If environment= whatever, then get this connection string".

services.AddDbContext<MyDbContext>(
         options => { options.UseSqlServer(@"Data Source=Txxx;Initial Catalog=xxx;Integrated Security=True"); });

只需检查 configuration documentation,我想你正在使用 Asp Net Core,并且你正在启动时添加 Mvc

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    ...
    app.UseMvc();
    ...
}

默认会尝试加载2个配置文件,appsettings.jsonappsettings.{Environment}.json,最新的会覆盖最终配置的内容,而且默认情况下,core已经有两个环境, developmentproduction,一切都取决于您使用的配置文件(在 visual studio 中默认为开发)。

因此,您的配置文件可以重命名为 appsettings.json,然后声明用于生产的连接字符串,并创建一个文件 appsettings.Development.json,您可以使用开发连接字符串覆盖连接。

您还可以加载更多文件或更改默认文件,方法如下

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.SetBasePath(Directory.GetCurrentDirectory());
            config.AddInMemoryCollection(arrayDict);
            config.AddJsonFile("json_array.json", optional: false, reloadOnChange: false);
            config.AddJsonFile("starship.json", optional: false, reloadOnChange: false);
            config.AddXmlFile("tvshow.xml", optional: false, reloadOnChange: false);
            config.AddEFConfiguration(options => options.UseInMemoryDatabase("InMemoryDb"));
            config.AddCommandLine(args);
        })
        .UseStartup<Startup>();

如果要环境变量

Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT ")

但是请考虑更安全

对于敏感数据,更安全的方法可能是将您的连接字符串配置为服务器中的环境变量,这样它可以从您的代码中删除并保持更私密。

可以在 secrets documentation.

中找到这个和其他使用秘密管理器的解决方案

编辑

Otherwise, it defaults to the "appSettings.json" file (this would be in production)

不,它不会加载一个或另一个,首先它会加载 appsettings.json,无论您有什么环境,它总是这样。

然后,在加载 appsettings.json 后,它将尝试加载 appsettings.{Environment}.json 并添加之前不存在的键,如果存在,它将覆盖旧键。

如果您在 appSettings

{
  "SomeConfigJustInAppSettings": "some value",
  "ThisWillBeOverride": "some value"
}

还有你的appsettings.Development.json

{
  "SomeConfigJustInDev": "some other value",
  "ThisWillBeOverride": "some other value"
}

你在开发中的配置最终会是:

{
  "SomeConfigJustInAppSettings": "some value",
  "SomeConfigJustInDev": "some other value",
  "ThisWillBeOverride": "some other value"
}

what determines what "ASPNETCORE_ENVIRONMENT" holds?

是一个 environmental variable,在操作系统中设置。此外,对于开发 Visual studio 可以在您开发应用程序时预加载一些变量,只需检查您的 launchSettings.json,例如:

{
  "profiles": {
    "MyProject": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:50051"
    },
    "Docker": {
      "commandName": "Docker",
      "launchBrowser": true,
      "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}"
    }
  }
}

特别是这部分

"environmentVariables": {
  "ASPNETCORE_ENVIRONMENT": "Development"
},

It would be nice to just find what the server name is and use that. Because I would only check for my dev box servername, everything else would mean production

现在更简单了,如果变量不存在,它只加载可能包含您的产品设置的应用程序设置。当你在开发时,visual studio(或 VS code,或 Rider)已经在添加值为 Development 的变量,因此你需要做的就是添加文件 appsettings.Development.json

见鬼,你甚至可以只创建一个新项目,默认的项目布局已经为你创建了这两个文件!