代码之家  ›  专栏  ›  技术社区  ›  Kirsten

为的连接字符串引用单独的文件appsettings.json?

  •  1
  • Kirsten  · 技术社区  · 6 年前

    在我的.NETFramework项目中,我喜欢在我的应用程序配置

     <connectionStrings configSource="connections.config" />
    

    与连接.config包含类似

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

    通过

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

    我该怎么做?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Henk Mollema    6 年前

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

    看一看 the docs 对于所有支持的配置提供程序。

        2
  •  1
  •   Elnoor    5 年前

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