Parameter configuration and use ASP.NET Core application (reprint)

The paper is organized


  1. Prepare in advance
  2. Parameter configuration
    1. appsettings.json
    2. Environment Variables
    3. Command line parameters
  3. Configuration parameters used in the controller
    1. Object injection IConfiguration
    2. Object injection IOptions
  4. to sum up

 

Application development is not just writing code this thing. Suppose you are developing a micro capable of supporting multiple deployment services, then you will need to have a reasonable application configuration program, to be able to easily choose different configuration parameters in the development and production environments, and able to be deployed in a container a service (such as ACS or Kubernetes), these parameters can be dynamically and rationally provided. In this paper, different configurations ASP.NET Core applications are introduced through the simplest form, and describes how to use these configuration parameters in the application, I believe that ASP.NET Core developers will be very helpful.

 

 

Prepare in advance


After we first use Visual Studio 2017 to create a new ASP.NET Core application, of course, if there is no Visual Studio 2017, then download and install the .NET Core SDK, use dotnet new command can also create ASP.NET Core application, and then you use usually accustomed to using the editor code editor. I still recommend the use of Visual Studio 2017, Community Edition (Community Edition) is completely free, with the Professional Edition and Enterprise Edition also not much different functionality. Free universe strongest IDE, stood not it be a waste it.

 

Closer to home, in order to be able to easily see ASP.NET Core applications use configuration data, we first modify Startup.cs file, add the code log console output. The key code is as follows:

public class Startup
{
    private readonly ILogger logger;
 
    public Startup(IConfiguration configuration, ILogger<Startup> logger)
    {
        Configuration = configuration;
        this.logger = logger;
    }
 
    public IConfiguration Configuration { get; }
 
    public void ConfigureServices(IServiceCollection services)
    {
        var mongoHost = Configuration["mongo:server:host"];
        logger.LogInformation("The Host Server MongoDB: " + mongoHost);
         // .... .... omitted other code 
    } 
}

Next, we can begin to do the experiment.

 

 

Parameter configuration


ASP.NET Core provides a variety of configuration parameters, sum up, there are several commonly used parameters configuration:

  • By appsettings.json file
  • Use system environment variables
  • Through the command line parameter configuration

Of course, also be custom profile or other configurations. But here I only intend to introduce conventional usage, because I believe that the current ASP.NET Core configuration provided by default should be able to meet most application scenarios. For more detailed information on other configuration parameters, refer to Microsoft's official documentation .

 

appsettings.json

appsettings.json file is ASP.NET Core application's configuration file, usually with the application DLL files in the same directory. You can specify which appsettings.json specific use as a configuration file by ASPNETCORE_ENVIRONMENT environment variable. For example, if the environment variable is ASPNETCORE_ENVIRONMENT Production, then appsettings.Production.json file will be used. This is determined according to the profile of the environment variable manner, allowing to determine the value of a number of parameters by a simple string, in practical use is very convenient.

 

Now, we modify appsettings.json file to configure the connection information into the MongoDB:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  },
  "AllowedHosts": "*",
  "mongo": {
    "server": {
      "host": "localhost",
      "port": 27017
    },
    "database": "db"
  }
}

Then compile the application, and copy the files to compile appsettings.json output directory, then start the application from the command line by dotnet command:

Can be seen, the configuration data have been normal output. Next, confirm ASPNETCORE_ENVIRONMENT specifies Development, therefore, we modify appsettings.Development.json file, using the same connection information structural configuration of MongoDB, but we use localhost_dev to specify mongo: server: host values:

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
 
  "mongo": {
    "server": {
      "host": "localhost_dev",
      "port": 27017
    },
    "database": "db"
  }
}

At this point, start the application again and found that the configuration data has been updated:

Thus, files can be used appsettings.json to choose to use a different configuration parameters according to different operating environment.

 

Environment Variables

appsettings.json file has been configured parameters, environment variables can be covered. We can set command to set an environment variable in the Windows command line:

Run the application again, the results obtained parameter value is set by the environment variable:

可以看出,之前由appsettings.json文件指定的参数,已经被环境变量所覆盖。这一特性十分重要,当我们把一个ASP.NET Core应用程序包装成一个docker镜像,并在docker容器中运行时,我们可以方便地使用docker run -e的参数,将环境变量注入进去,并覆盖原来写死在配置文件中的值,这也充分证明了ASP.NET Core对于容器的支持是十分友好的。

 

命令行参数

在使用dotnet启动应用程序时,可以直接在命令行提供运行时参数,此时命令行参数会覆盖环境变量中的设置,比如:

同样,如果ASP.NET Core应用程序被包装成一个docker镜像,那么我们就可以通过docker exec命令对应用程序进行调试,并直接通过命令行注入调试时所需的参数。

 

 

在控制器中使用配置参数


要在控制器中使用配置参数,最常用的有两种方法,第一种是在控制器的构造函数中注入IConfiguration对象,另一种则是自定义一个配置数据模型,然后在控制器的构造函数中注入IOptions对象。

 

注入IConfiguration对象

以下代码演示了通过构造器注入IConfiguration对象的方式来获取配置信息:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly IConfiguration configuration;
 
    public ValuesController(IConfiguration configuration)
    {
        this.configuration = configuration;
    }
 
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { this.configuration["mongo:server:host"] };
    }
}

执行结果如下:

 

注入IOptions对象

这种方法首先需要根据配置数据的结构,自定义一个用于保存配置数据的类:

public class Server
{
    public string Host { get; set; }
 
    public int Port { get; set; }
}
 
public class Mongo
{
    public Server Server { get; set; }
 
    public string Database { get; set; }
}

然后,修改Startup.ConfigureServices方法,将配置注入进来:

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.Configure<Mongo>(Configuration.GetSection("mongo"));
    // ...
}

最后,在控制器的构造函数中注入IOptions对象:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly IOptions<Mongo> configuration;
 
    public ValuesController(IOptions<Mongo> configuration)
    {
        this.configuration = configuration;
    }
 
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { this.configuration.Value.Server.Host };
    }
}

执行结果也是一样的:

 

Guess you like

Origin www.cnblogs.com/OpenCoder/p/11199978.html