How to set Environment Name (IHostingEnvironment.EnvironmentName)?

后端 未结 11 943
耶瑟儿~
耶瑟儿~ 2020-12-04 16:06

Default ASP.NET Core web project contain such lines in Startup.cs:

if (string.Equals(env.EnvironmentName, \"Development\", StringComparison.Ordi         


        
相关标签:
11条回答
  • 2020-12-04 16:55

    After RC2

    So what is the way to set a different EnvironmentName?

    Set the ASPNETCORE_ENVIRONMENT environmental variable.

    There are many ways to set that environmental variable. These include a launchSettings.json profile and other environment-specific ways. Here are some examples.

    From a console:

    // PowerShell
    > $env:ASPNETCORE_ENVIRONMENT="Development"
    
    // Windows Command Line
    > SET ASPNETCORE_ENVIRONMENT=Development
    
    // Bash
    > ASPNETCORE_ENVIRONMENT=Development
    

    From an Azure Web App's App settings:

    Before RC2

    I can imagine that it should be set in "Commands" as a parameter for server.

    That is true. In your project.json, add --ASPNET_ENV production as a parameter for the server.

    "commands": {
      "web": "Microsoft.AspNet.Hosting --ASPNET_ENV production --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001"
    }
    

    Now when you run dnx . web from the command line, ASPNET_ENV will be production.

    Relevant ASP.NET Core Hosting Source Code

    The WebHostBuilder combines "ASPNETCORE_" with the WebHostDefaults.EnvironmentKey to make "ASPNETCORE_environment". It also supports the legacy keys.

    WebHostDefaults.cs

    namespace Microsoft.AspNetCore.Hosting
    {
        public static class WebHostDefaults
        {
            public static readonly string ApplicationKey = "applicationName";
            public static readonly string StartupAssemblyKey = "startupAssembly";
    
            public static readonly string DetailedErrorsKey = "detailedErrors";
            public static readonly string EnvironmentKey = "environment";
            public static readonly string WebRootKey = "webroot";
            public static readonly string CaptureStartupErrorsKey = "captureStartupErrors";
            public static readonly string ServerUrlsKey = "urls";
            public static readonly string ContentRootKey = "contentRoot";
        }
    }
    

    WebHostBuilder.cs

    _config = new ConfigurationBuilder()
        .AddEnvironmentVariables(prefix: "ASPNETCORE_")
        .Build();
    
    if (string.IsNullOrEmpty(GetSetting(WebHostDefaults.EnvironmentKey)))
    {
        // Try adding legacy environment keys, never remove these.
        UseSetting(WebHostDefaults.EnvironmentKey, 
            Environment.GetEnvironmentVariable("Hosting:Environment") 
            ?? Environment.GetEnvironmentVariable("ASPNET_ENV"));
    }
    

    Backward Compatibility

    The environment key is set with the ASPNETCORE_ENVIRONMENT environment variable. ASPNET_ENV and Hosting:Environment are still supported, but generate a deprecated message warning.

    https://docs.asp.net/en/latest/migration/rc1-to-rtm.html

    Default Value

    The default value is "Production" and is set here.

    0 讨论(0)
  • 2020-12-04 16:58

    launchsettings.json

    At Properties > launchsettings.json

    Just like this:

        {
      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://localhost:1032/",
          "sslPort": 0
        }
      },
      "profiles": {
        "IIS Express": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Production"
          }
        },
        "WebAppNetCore": {
          "commandName": "Project",
          "launchBrowser": true,
          "launchUrl": "http://localhost:5000",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        },
        "web": {
          "commandName": "web",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-04 16:59

    I had same problem. To to be independet to enviroment variable and web.config, I created a .json file as (I called it envsettings.json):

    {
      // Possible string values reported below.
      // - Production
      // - Staging
      // - Development
      "ASPNETCORE_ENVIRONMENT": "Staging"
    }
    

    Then in Program.cs I added:

    public class Program
    {
        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 enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();
    
            var webHostBuilder = new WebHostBuilder()
                .UseKestrel()
                .CaptureStartupErrors(true)
                .UseSetting("detailedErrors", "true")
                .UseContentRoot(currentDirectoryPath)
                .UseIISIntegration()
                .UseStartup<Startup>();
    
            // If none is set it use Operative System hosting enviroment
            if (!string.IsNullOrWhiteSpace(enviromentValue)) 
            {
                webHostBuilder.UseEnvironment(enviromentValue);
            }
    
            var host = webHostBuilder.Build();
    
            host.Run();
        }
    }
    
    0 讨论(0)
  • 2020-12-04 17:00
    1. On Azure just set ASPNET_ENV environment variable on web app configuration page.

    2. With your own IIS or other hosting providers - modify web.config to include arguments for "web" command:

      <configuration>
       <system.webServer>
        <handlers>
          <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
        </handlers>
        <httpPlatform processPath="..\approot\web.cmd" arguments="--ASPNET_ENV Development" stdoutLogEnabled="false" stdoutLogFile="..\logs\stdout.log" startupTimeLimit="3600"></httpPlatform>
       </system.webServer>
      </configuration>
      
    3. During development (if you can modify source code), you can also create file named Microsoft.AspNet.Hosting.json in a root of your project and set the ASPNET_ENV variable.

      { "ASPNET_ENV": "Test" }

    0 讨论(0)
  • 2020-12-04 17:01

    In ASP.NET Core RC2 the variable name is has been changed to ASPNETCORE_ENVIRONMENT

    e.g. In Windows you can execute this command on the staging server (with admin rights)

    SETX ASPNETCORE_ENVIRONMENT "Staging" /M
    

    This only has be be executed once and after that, the server will always be considered as the staging server.

    When you do a dotnet run in the command prompt on that server you will see Hosting environment: Staging

    0 讨论(0)
提交回复
热议问题