C# 如何设置发布asp.net核心应用程序时要考虑的ASPNETCORE_环境?

C# 如何设置发布asp.net核心应用程序时要考虑的ASPNETCORE_环境?,c#,asp.net-core,environment-variables,C#,Asp.net Core,Environment Variables,当我将asp.net core web应用程序发布到本地文件系统时,它总是使用production config和ASPNETCORE_环境变量,其值为=“production” 如何以及在何处设置ASPNETCORE_环境变量的值,以便不仅在调试时考虑它,而且在发布时也考虑它?我已经尝试了以下选项,但没有成功: 在windows设置中 在.pubxml文件中 在launchSettings.json中 在project.json中 选项1: 要在windows中设置ASPNETCORE_环境

当我将asp.net core web应用程序发布到本地文件系统时,它总是使用production config和ASPNETCORE_环境变量,其值为=“production”

如何以及在何处设置ASPNETCORE_环境变量的值,以便不仅在调试时考虑它,而且在发布时也考虑它?我已经尝试了以下选项,但没有成功:

  • 在windows设置中
  • 在.pubxml文件中
  • 在launchSettings.json中
  • 在project.json中

选项1:

要在windows中设置ASPNETCORE_环境变量

命令行-
setx ASPNETCORE\u环境“开发”

PowerShell-
$Env:ASPNETCORE_ENVIRONMENT=“Development”

有关其他操作系统,请参阅以下内容:

选项2:

如果您想使用
web.config
设置ASPNETCORE\u环境,请像这样添加
ASPNETCORE
-


您应该遵循,使用
web.config

<aspNetCore processPath="dotnet"
        arguments=".\MyApp.dll"
        stdoutLogEnabled="false"
        stdoutLogFile="\\?\%home%\LogFiles\aspnetcore-stdout">
  <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Production" />
    <environmentVariable name="CONFIG_DIR" value="f:\application_config" />
  </environmentVariables>
</aspNetCore>

请注意,您还可以设置其他环境变量

ASP.NET核心模块允许您为指定环境变量 通过指定processPath属性中指定的进程 在一个或多个环境变量的子元素中 aspNetCore元素下的environmentVariables集合元素。 本节中设置的环境变量优先于系统变量 流程的环境变量


在visual studio IDE中设置它的简单方法。

项目>属性>调试>环境变量


使用最新版本的dotnet cli(2.1.400或更高版本),您只需设置此msbuild属性
$(EnvironmentName)
,发布工具将负责使用环境名称将ASPNETCORE\u环境添加到web.config中

此外,XDT支持从2.2.100-preview1开始提供


示例:

除了上面提到的选项之外,还有一些其他解决方案

1。修改项目文件(.CsProj)文件

MSBuild支持
EnvironmentName
属性,该属性有助于根据要部署的环境设置正确的环境变量。在发布阶段,环境名称将添加到web.config中

只需打开项目文件(*.csProj)并添加以下XML即可

<!-- Custom Property Group added to add the Environment name during publish
  The EnvironmentName property is used during the publish for the Environment variable in web.config
  -->
  <PropertyGroup Condition=" '$(Configuration)' == '' Or '$(Configuration)' == 'Debug'">
    <EnvironmentName>Development</EnvironmentName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)' != '' AND '$(Configuration)' != 'Debug' ">
    <EnvironmentName>Production</EnvironmentName>
  </PropertyGroup>
3。使用dotnet发布的命令行选项

另外,我们可以将属性
EnvironmentName
作为命令行选项传递给
dotnet publish
命令。以下命令将在web.config文件中包含环境变量
Development


dotnet publish-c Debug-r win-x64/p:EnvironmentName=Development

我们可以在运行时设置它:

public class Program
{
    public static void Main(string[] args)
    {
        Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");

        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}
公共类程序
{
公共静态void Main(字符串[]args)
{
SetEnvironmentVariable(“ASPNETCORE_环境”、“开发”);
BuildWebHost(args.Run();
}
公共静态IWebHost BuildWebHost(字符串[]args)=>
WebHost.CreateDefaultBuilder(args)
.UseStartup()
.Build();
}

通过直接在Azure platorm上设置此变量(如果您使用它),我发现它对我有效。只需选择web应用程序->配置->应用程序设置并添加变量及其值,然后按保存按钮。

此变量可以保存为json格式。例如envsettings.json 内容如下

  {
   // Possible string values reported below. When empty it use ENV variable value or 
     // Visual Studio setting.
     // - Production
     // - Staging
     // - Test
     // - Development

   "ASPNETCORE_ENVIRONMENT": "Development"
  }
  public class Program
  {
    public static IConfiguration Configuration { get; set; }
    public static void Main(string[] args)
    {
        var currentDirectoryPath = Directory.GetCurrentDirectory();
        var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
        var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
        var environmentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();

        var builder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
          var webHostBuilder = new WebHostBuilder()
            .UseKestrel()
            .CaptureStartupErrors(true)
            .UseContentRoot(currentDirectoryPath)
            .UseIISIntegration()
            .UseStartup<Startup>();

        // If none is set it use Operative System hosting enviroment
        if (!string.IsNullOrWhiteSpace(environmentValue))
        {
            webHostBuilder.UseEnvironment(environmentValue);
        }

        var host = webHostBuilder.Build();

        host.Run();
     }
 }
稍后修改program.cs,如下所示

  {
   // Possible string values reported below. When empty it use ENV variable value or 
     // Visual Studio setting.
     // - Production
     // - Staging
     // - Test
     // - Development

   "ASPNETCORE_ENVIRONMENT": "Development"
  }
  public class Program
  {
    public static IConfiguration Configuration { get; set; }
    public static void Main(string[] args)
    {
        var currentDirectoryPath = Directory.GetCurrentDirectory();
        var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
        var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
        var environmentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();

        var builder = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
          var webHostBuilder = new WebHostBuilder()
            .UseKestrel()
            .CaptureStartupErrors(true)
            .UseContentRoot(currentDirectoryPath)
            .UseIISIntegration()
            .UseStartup<Startup>();

        // If none is set it use Operative System hosting enviroment
        if (!string.IsNullOrWhiteSpace(environmentValue))
        {
            webHostBuilder.UseEnvironment(environmentValue);
        }

        var host = webHostBuilder.Build();

        host.Run();
     }
 }
公共类程序
{
公共静态IConfiguration配置{get;set;}
公共静态void Main(字符串[]args)
{
var currentDirectoryPath=Directory.GetCurrentDirectory();
var envSettingsPath=Path.Combine(currentDirectoryPath,“envsettings.json”);
var envSettings=JObject.Parse(File.ReadAllText(envSettingsPath));
var environmentValue=envSettings[“ASPNETCORE_ENVIRONMENT”]。ToString();
var builder=new ConfigurationBuilder()
.SetBasePath(目录.GetCurrentDirectory())
.AddJsonFile(“appsettings.json”);
Configuration=builder.Build();
var webHostBuilder=新的webHostBuilder()
.UseKestrel()
.CaptureStartupErrors(真)
.UseContentRoot(currentDirectoryPath)
.Useii整合()
.UseStartup();
//如果未设置,则使用操作系统托管环境
如果(!string.IsNullOrWhiteSpace(environmentValue))
{
webHostBuilder.UseEnvironment(environmentValue);
}
var host=webHostBuilder.Build();
host.Run();
}
}
这样,它将始终包含在发布中,您可以根据网站所在的环境更改为所需的值。
此方法也可以在console应用程序中使用,因为在Program.cs中有更改。为了能够设置每个站点的环境,我们在项目中使用的其他选项是向项目添加Parameters.xml文件,其中包含以下内容:

<parameters>
      <parameter name="IIS Web Application Name" defaultValue="MyApp" tags="IisApp" />    
      <parameter name="Environment" description="Environment" tags="">
        <parameterEntry kind="XmlFile" scope="Web.config"  match="/configuration/location/system.webServer/aspNetCore/environmentVariables/environmentVariable[@name='ASPNETCORE_ENVIRONMENT']/@value" />
      </parameter>    
</parameters>

通过这种方式,我们可以有多个版本,都使用相同的工件,但部署为不同的环境。

我知道这是一篇老文章,但我认为我会将我的简单解决方案加入其中,因为没有人提出它

我使用当前目录确定当前环境,然后翻转连接字符串和环境变量。只要您对站点文件夹(如test/beta/sandbox)有一个命名约定,这就非常有效

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var dir = Environment.CurrentDirectory;
        string connectionString;

        if (dir.Contains("test", StringComparison.OrdinalIgnoreCase))
        {
            connectionString = new ConnectionStringBuilder(server: "xxx", database: "xxx").ConnectionString;
            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
        }
        else
        {
            connectionString = new ConnectionStringBuilder(server: "xxx", database: "xxx").ConnectionString;
            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Production");
        }

        optionsBuilder.UseSqlServer(connectionString);
        optionsBuilder.UseLazyLoadingProxies();
        optionsBuilder.EnableSensitiveDataLogging();
    }
  • 创建appsettings.*.json文件。(示例:appsettings.Development.json、appsettings.Staging.json、,
        <PropertyGroup>
          <EnvironmentName>Development</EnvironmentName>
        </PropertyGroup>
    
    static async Task Main(string[] args)
    {
       ...
       //set the environment variable based on App Settings
       var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
       builder.UseEnvironment(environment);
    
    <!-- Adds EnvironmentName variable during publish -->
    <PropertyGroup Condition="'$(Configuration)' == 'Debug'">
        <EnvironmentName>Development</EnvironmentName>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Configuration)' == 'Release'">
        <EnvironmentName>Production</EnvironmentName>
    </PropertyGroup>