【问题标题】:Referring to a separate file for connection strings for appsettings.json?引用 appsettings.json 的连接字符串的单独文件?
【发布时间】:2019-09-07 06:49:08
【问题描述】:

在我的 .net 框架项目中,我喜欢在我的 app.config 中包含以下内容

 <connectionStrings configSource="connections.config" />

connections.config 包含类似

的内容
 <connectionStrings>

   <add name="ApplicationDatabase" providerName="System.Data.SqlClient" connectionString="Server=.\SQLEXPRESS;Database=mydatabase;User Id=myuser; PWD=mypassword;"  />

</connectionStrings>

那我就不把connections.config检入源代码了。

我想对 .NET Core 使用类似的技巧,但它使用了 appsettings.json

通过

     services.AddDbContext<ApiDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("MyDatabase")));

我该怎么做?

【问题讨论】:

标签: json asp.net-core


【解决方案1】:

您可以创建一个单独的 JSON 文件(或 XML,或任何配置提供程序)并在应用程序启动时加载:

WebHost.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration(builder =>
    {
        builder.AddJsonFile("connectionstrings.json", optional: true);
    })

查看the docs 了解所有受支持的配置提供程序。

【讨论】:

    【解决方案2】:

    对于那些想要保护连接字符串(或任何其他敏感值)时遇到类似情况的人,可以简单地使用User Secrets。在 Visual Studio(2019 年测试)中,右键单击项目,然后单击“管理用户机密”将打开 secrets.json 文件,该文件是一个隐藏文件。可以像 appsettings.json 文件一样在此处输入键/值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      相关资源
      最近更新 更多