Detailed explanation of flexible configuration in asp.net core

Time:2021-7-14

preface

Asp.net core supports external files and command-line parameters to configure the configuration information needed by system operation. Let’s talk about the specific usage from the following two common scenarios.

1、 Monitor address and port configuration

1. Command line mode

Asp.net core system is started by command line. The commands used are as follows:

dotnet run

The above command is executed directly in the source code directory, and the program can be compiled and run. For the released program, the above instructions can not be used, but the following instructions should be used:

Dotnet assembly file name (the assembly file name is the DLL file generated after the program is published)

Both of the above instructions can start the application. After the program starts, the default listening address and port are http://localhost:5000 。 But after the program is released, it will not use the default address and port. What if you want to listen to other addresses or domain names at startup? The answer is to use the — URLs parameter. The specific instruction format is as follows:

Dotnet run -- URLs = "http: // Domain Name: port number"

If you want to set up multiple domain names, you can use semicolons to separate them.

The program does not support parameter passing by default. We need to configure the program. First, we need to introduceMicrosoft.Extensions.Configuration.CommandLineThen add the command line support in the main method. The specific code is as follows:

public class Program

 {

  public static void Main(string[] args)

  {

   var config = new ConfigurationBuilder()

   . addcommandline (args) // add command line support

   .Build();

 

   var host = new WebHostBuilder()

    .UseConfiguration(config)

    .UseKestrel()

    .UseContentRoot(Directory.GetCurrentDirectory())

    .UseIISIntegration()

    .UseStartup<Startup>()

    .UseApplicationInsights()

    .Build();

 

   host.Run();

  }

 }

After configuration, you can use the above instructions to pass parameters

2. Configuration file

Asp.net core configuration information can also be placed in a configuration file. When the system starts, the content of the configuration file will be loaded to affect the environment parameters needed for the program to start. Let’s take a look at the specific operation process.

First, we need to introduce a library file “Microsoft. Extensions. Configuration. JSON”, and then introduce the configuration file path information in the main method. The specific code is as follows:


public class Program

{

 public static void Main(string[] args)

 {

  var config = new ConfigurationBuilder()

   .SetBasePath(Directory.GetCurrentDirectory())

   .AddJsonFile("hosting.json")

   .Build();

 

  var host = new WebHostBuilder()

   .UseConfiguration(config)

   .UseKestrel()

   .UseContentRoot(Directory.GetCurrentDirectory())

   .UseIISIntegration()

   .UseStartup<Startup>()

   .UseApplicationInsights()

   .Build();

 

  host.Run();

 }

} 

Through the above method, we add an external hosting.json configuration file, in which we can add listening address information, as follows:


{

 "server.urls": "http://*:5001"

} 

2、 Running environment configuration

In project development, the separation of development environment, test environment and formal environment is often required, and the running parameters of different environments are different, such as listening address, database connection information, etc. Of course, we save the configuration information in a file. Every time we publish, we can modify the content of the configuration file first, and then publish the program. This operation is undoubtedly very troublesome. Every time we publish, we have to determine the corresponding environment, and then modify the configuration information. If we need to publish multiple environment versions at the same time, we have to do many operations.

Asp.net core has actually considered such a scenario. Let’s look at the following code first:


public Startup(IHostingEnvironment env)

  {

   var builder = new ConfigurationBuilder()

    .SetBasePath(env.ContentRootPath)

    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)

    .AddEnvironmentVariables();

   Configuration = builder.Build();

  } 

The above code appears in the startup. CS file, which is used firstAddJsonFile("appsettings.json", optional: false, reloadOnChange: true)Load the Appsettings configuration file, which can hold the information shared by all environments. There is a sentence after itAddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)env.EnvironmentNameIn fact, it is the system environment. According to the environmentname set at startup, the corresponding configuration file can be loaded.

Now the question is how to specify the environmentname?

1, specify the environment through the command line

Before executing dotnet run, you can execute the following instructions:

set ASPNETCORE_ENVIRONMENT=Environment name. Note that there are no quotation marks here. Just write the environment name as a specific value, such as set ASPNETCORE_ENVIRONMNET=development

And then do itdotnet runIn this way, the current run will run according to the environment set in the set instruction

2. Directly pass specific parameters to the dotnet run instruction

First look at the direct implementation effect:dotnet run --ASPNETCORE_ENVIRONMENT=development

Specific methods:Introducing microsoft.extensions.configuration.commandlineMicrosoft.Extensions.Configuration.EnvironmentVariablesThen add the support of environment parameters in the main method. The specific code is as follows:


public class Program

{

 public static void Main(string[] args)

 {

  var config = new ConfigurationBuilder()

   .AddEnvironmentVariables()

   .AddCommandLine(args)

   .SetBasePath(Directory.GetCurrentDirectory())

   .AddJsonFile("hosting.json")

   .Build();

 

  var host = new WebHostBuilder()

   .UseEnvironment(config["ASPNETCORE_ENVIRONMENT"])

   .UseConfiguration(config)

   .UseKestrel()

   .UseContentRoot(Directory.GetCurrentDirectory())

   .UseIISIntegration()

   .UseStartup<Startup>()

   .UseApplicationInsights()

   .Build();

 

  host.Run();

 }

} 

The point isAddEnvironmentVariables(),UseEnvironment(config["ASPNETCORE_ENVIRONMENT"])Treatment of the two places. So that we can work togetherdotnet runAdd the corresponding environment parameter after the instruction.  

summary

The above is the whole content of this article, I hope the content of this article can bring some help to your study or work, if you have any questions, you can leave a message to exchange, thank you for your support to developer.