Implementation of ASP. NET Core Configuration and Use Environment Variables

  • 2021-11-14 05:20:17
  • OfStack

Preface

Usually, from application development to official launch, we will divide into several stages in this process, usually including development, testing, and official environment. We will use different parameters for each environment parameter configuration. Therefore, the related environment API is provided in ASP. NET Core, which is convenient for us to do these things better.

Environment

ASP. NET Core uses ASPNETCORE_ENVIRONMENT to identify the runtime environment.

ASP. NET Core preset environment

Development: Development Environment Staging: Staging Environment (Test Environment) Production: Formal Environment

To get the system variable ASPNETCORE_ENVIRONMENT, you can get it by injecting IHostingEnvironment before version 3.0, and 3. x via IWebHostEnvironment see the following code snippet:


  public class Startup
  {
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment())
      {
      }

      app.Run(async (context) =>
      {
        await context.Response.WriteAsync(
          $"EnvironmentName: {env.EnvironmentName},IsDevelopment: {env.IsDevelopment()}"
        );
      });
    }
  }

IWebHostEnvironment will get the content from ASPNETCORE_ENVIRONMENT after the site starts, and this variable can be any value we need. That is to say, the variable is not 1, but 1 is the default value, and we can customize it.

For example, we define an environment named Test


   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      env.EnvironmentName = "test";

      if (env.IsDevelopment())
      {
        //TODO
      }else if (env.IsEnvironment("text"))
      {
        //TODO
      }

      app.Run(async (context) =>
      {
        await context.Response.WriteAsync(
          $"EnvironmentName: {env.EnvironmentName},IsDevelopment: {env.IsDevelopment()}"
        );
      });
 }

Note: On Windows and macOS, environment variables and values are not case sensitive. By default, Linux environment variables and values are case sensitive.


    public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostContext, config) =>
        {
          var env = hostContext.HostingEnvironment;
          config.SetBasePath(Path.Combine(env.ContentRootPath, "Configuration"))
            .AddJsonFile(path: "settings.json", optional: false, reloadOnChange: true)
            .AddJsonFile(path: $"settings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
          webBuilder.UseStartup<Startup>();
        });

Through the above code, we read our configuration file echo read setting. json and set it to optional: false, indicating that the configuration is necessary; Read on and read the settings. {env. EnvironmentName}. json file. When the load encounters the same Key, the previous configuration item will be overwritten.

SetBasePath: Set the directory location of the configuration. If it is placed in a different directory, change the path. AddJsonFile: path: The path location of the file. optional: If it is a necessary configuration file, set it to false optionally, and raise FileNotFoundException when the file does not exist. reloadOnChange: If the file is updated, the value of the IConfiguration instance is updated synchronously.

Environment settings

IIS

web. config Configuration Environment Variable


<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
  <handlers>
   <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
  </handlers>
  <aspNetCore processPath="dotnet" arguments=".\Demo.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout">
   <environmentVariables>
    <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Test" />
   </environmentVariables>
  </aspNetCore>
 </system.webServer>
</configuration>

Visual Studio Code

ASPNETCORE_ENVIRONMENT configured in launch. json


{
  "version": "0.1.0",
  "configurations": [
    {
      "name": ".NET Core Launch (web)",
      "type": "coreclr",
      "env": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  ]
}

Visual Studio IDE

Properties\launchSettings.json


 "profiles": {
  "IIS Express": {
   "commandName": "IISExpress",
   "launchBrowser": true,
   "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Test"
   }
  },
  }

Related articles: