Detailed description of flexible configuration methods in asp.net core, asp. netcore

Source: Internet
Author: User

Detailed description of flexible configuration methods in asp.net core, asp. netcore

Preface

Asp.net core supports external files and command line parameters to configure the configuration information required for system running. The following two common scenarios describe how to use them.

I. Listener address and port configuration

1. Command Line

The asp.net core system is started using the command line as follows:

dotnet run

The preceding command can be directly executed in the source code directory to compile and run the program. The preceding commands cannot be used for published programs. The following commands should be used:

Dotnet Assembly file name (Assembly file name is the dll file generated after the program is released)

Both of the preceding commands can start the application. After the program starts, the default listening address and port are http: // localhost: 5000. However, the default address and port will not be used after the program is released. What if I want to listen to other addresses or domain names at startup? The answer is to use the -- urls parameter. The command format is as follows:

Dotnet run -- urls = "http: // Domain Name: Port Number"

To set multiple domain names, use semicolons to separate them.

By default, the program does not support parameter passing. We need to configure the program. First, introduceMicrosoft.Extensions.Configuration.CommandLineLibrary file, and then add commandline 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) // added commandline 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 preceding command to pass parameters.

2. Configuration File

Asp.net core configuration information can also be stored in a configuration file. When the system starts, the content of the configuration file is loaded to affect the environment parameters required for program startup. 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(); }} 

In the preceding method, an external hosting. json configuration file is added, in which we can add the listener address information, as shown below:

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

Ii. runtime environment Configuration

During project development, the development environment, test environment, and formal environment are often required to be separated, and parameters running in different environments are different, such as the listening address and database connection information. Of course, we save the configuration information to a file. During each release, we can first modify the content of the configuration file and then release the program. This operation is undoubtedly very troublesome, each release requires you to determine the corresponding environment, and then modify the configuration information. If you need to release multiple environment versions at the same time, you have to perform multiple operations.

Asp.net core has taken such a scenario into consideration. Let's take a look at the following code:

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 first usesAddJsonFile("appsettings.json", optional: false, reloadOnChange: true)Load the appsettings configuration file, which contains information shared by all environments.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true),env.EnvironmentNameIt is actually the system environment. The corresponding configuration file content can be loaded according to the EnvironmentName set at startup.

The question is how to specify the EnvironmentName?

1. Specify environment through the command line

Before Running dotnet run, run the following command:

set ASPNETCORE_ENVIRONMENT= Environment name. Note that there are no quotation marks. You can directly write the environment name as a specific value, for example set ASPNETCORE_ENVIRONMNET=development

Then executedotnet runCommand, so that the current operation will run according to the environment set in the set command

2. directly pass specific parameters to the dotnet run Command.

First, let's look at the direct execution results:dotnet run --ASPNETCORE_ENVIRONMENT=development

Specific Practices:Introduce Microsoft. Extensions. Configuration. CommandLine,Microsoft.Extensions.Configuration.EnvironmentVariablesLibrary file, and then add support for 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 key isAddEnvironmentVariables(),UseEnvironment(config["ASPNETCORE_ENVIRONMENT"])Processing. In this way, we candotnet runAdd the corresponding environment parameters after the command.

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.