ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(
applicationEnvironment.ApplicationBasePath);
// Add configuration from the config.json file.
configurationBuilder.AddJsonFile("config.json");
// Add configuration from an optional config.development.json, config.staging.json or
// config.production.json file, depending on the environment. These settings override the ones in the
// config.json file.
configurationBuilder.AddJsonFile($"config.{hostingEnvironment.EnvironmentName}.json", optional: true);
if (hostingEnvironment.IsEnvironment(EnvironmentName.Development))
{
// This reads the configuration keys from the secret store. This allows you to store connection strings
// and other sensitive settings on your development environment, so you don't have to check them into
// your source control provider. See http://go.microsoft.com/fwlink/?LinkID=532709 and
// http://docs.asp.net/en/latest/security/app-secrets.html
configurationBuilder.AddUserSecrets();
}
// Add configuration specific to the Development, Staging or Production environments. This config can
// be stored on the machine being deployed to or if you are using Azure, in the cloud. These settings
// override the ones in all of the above config files.
// Note: To set environment variables for debugging navigate to:
// Project Properties -> Debug Tab -> Environment Variables
// Note: To get environment variables for the machine use the following command in PowerShell:
// $env:[VARIABLE_NAME]
// Note: To set environment variables for the machine use the following command in PowerShell:
// $env:[VARIABLE_NAME]="[VARIABLE_VALUE]"
// Note: Environment variables use a colon separator e.g. You can override the site title by creating a
// variable named AppSettings:SiteTitle. See
// http://docs.asp.net/en/latest/security/app-secrets.html
configurationBuilder.AddEnvironmentVariables();
IConfiguration configuration = configurationBuilder.Build();
3 回答
您不需要在ASP.NET 5中进行配置转换,因为它对链式配置源具有开箱即用的支持 . 例如,取this sample:
我们添加两个配置源并构建我们的配置 . 如果我要求配置密钥,它将尝试通过查看从最后到第一个订单的来源获取该密钥的值 . 在上面的例子中,我可以在开发期间使用config.json文件,我可以通过从环境变量提供适当的配置来实现这一点 .
有关更多信息,请查看the Configuration docs .
我知道web.configs并不是真的支持,但它们仍然在IIS下的ASP.Net中使用 .
我想要应用转换以及我想从配置中控制环境变量,如下所示:
如果你真的想在ASP.Net core / 5中转换它们,你可以使用以下方法:
根据需要为项目添加任意数量的不同web.config转换文件 . 例如,您可以添加Web.Development.config,Web.Staging.config和Web.Production.config等...无论您喜欢如何命名它们 .
修改project.json文件以通过将此行添加到当前web.config行下面的publishoptions来输出文件:“web . * . config”
创建发布配置文件并修改发布配置文件(位于Web Project \ Properties \ PublishProperties \ profilename-publish.ps1)的powershell脚本,以添加以下修改:
在try catch上面添加这个函数(我在这里找到了这个函数Web.Config transforms outside of Microsoft MSBuild?,略有修改 . ):
添加这些行 ABOVE Publish-AspNet调用:
如@tugberk所示,您可以使用环境变量,这是处理这种情况的更好方法 . 如果您在开发环境中运行并且想要存储密码或连接字符串,则还可以使用用户机密来添加它们 . 毕竟,你还可以使用像这样的特定于环境的配置文件(这是一个ASP.NET 5 Beta 5示例):