当前位置:网站首页>ASP. Net core configuration options (Part 1)

ASP. Net core configuration options (Part 1)

2022-04-23 17:06:00 begeneral

Previous configuration , Everyone will think of web.config and app.config, And there seems to be only one way . But in ASP.NET CORE in , It not only provides diversified configuration methods , And it provides monitoring function .

Here we will only introduce some of the most commonly used configuration methods , The most common configuration method should still be configuration file , After all, it is convenient to modify the configuration in this way , No need to recompile the code .

1、 Define configuration in appsettings.json In file

The configuration is as follows :

"format": {
    "dateTime": {
      "longDataPattern": "dddd,MMMM,d,yyyy",
      "longTimePattern": "h:mm:ss tt",
      "shortDataPattern": "M/d/yyyy",
      "shortTimePattern": "h:mm tt"
    },
    "currencyDecimal": {
      "digits": "5",
      "symbol": "$"
    }
  }

Then define a class consistent with the current structure :

public class FormatOptions
    {
        public DateTimeFormatOptions DateTime { get; set; }
        public CurrencyDecimalFormatOptions CurrencyDecimal { get; set; }     
    }
public class DateTimeFormatOptions
    {    
        public string LongDataPattern { get; set; }
        public string LongTimePattern { get; set; }
        public string ShortDataPattern { get; set; }
        public string ShortTimePattern { get; set; }
    }
public class CurrencyDecimalFormatOptions
    {
        public int Digits { get; set; }
        public string Symbol { get; set; }    
    }

stay startup Of ConfigureServices Method :

services.AddOptions().Configure<FormatOptions>(Configuration.GetSection("format"));

there Configuration Namely startup Global variable of class

public IConfiguration Configuration { get; }

This Configuration Included by default appsettings.json Content of profile , So we don't need to build a new one ourselves ConfigurationBuilder object , If our configuration is not defined in appsettings.json Inside , It's a custom one JSON file ,

Then we need to build a new one ConfigurationBuilder object , We'll talk about this later

Why call GetSection Methods? ? Because of our appsettings.json There are other configuration items in ( The default configuration item created by the framework when the project is created ), We only take what we want , If you don't call GetSection Words , Can't get

The value of the configuration item , Because there are no fields of the default configuration items of the framework in the class we define .

Now let's create a new controller , hold IOptions<FormatOptions> As an argument to the constructor , The code is as follows :

public class TestController : Controller
    {
        private readonly IOptions<FormatOptions> _options;
        public TestController(IOptions<FormatOptions> options)
        {
            _options = options;
        }
        public string Index()
        {
            var value = _options.Value;
            var dateTime = value.DateTime;
            var currencyDecimal = value.CurrencyDecimal;
            StringBuilder sb = new StringBuilder();
            sb.Append($"DateTime:");
            sb.Append($"\r\nlongDataPattern:{dateTime.LongDataPattern}");
            sb.Append($"\r\nlongTimePattern:{dateTime.LongTimePattern}");
            sb.Append($"\r\nshortDataPattern:{dateTime.ShortDataPattern}");
            sb.Append($"\r\nshortTimePattern:{dateTime.ShortTimePattern}");
            sb.Append($"\r\nCurrencyDecimal:");
            sb.Append($"\r\ndigits:{currencyDecimal.Digits}");
            sb.Append($"\r\nsymbol:{currencyDecimal.Symbol}");

            return sb.ToString();
        }
    }

2、 Custom configuration files

In some cases , We may need to define the configuration file in our custom JSON In file . Let's build a new profile.json file , The configuration is as follows :

{
  "gender": "Male",
  "age": "33",
  "contactinfo": {
    "emailAddress": "foobar.outlook.com",
    "phoneno": "123456789"
  }
}

stay startup Class ConfigureServices Method :

var configuration = new ConfigurationBuilder().AddJsonFile(path:"profile.json",optional:false,reloadOnChange:true).Build();
services.AddOptions().Configure<Profile>(configuration);

path: Indicates the path of the configuration file ;optional Indicates whether the configuration file is optional , If so , When the program starts, the framework will not check whether the file exists , And even without this file , The program will not report a mistake , frame

It will also assign a default value to all fields of the class corresponding to this configuration . If optional , The framework checks whether the file exists , If it doesn't exist, it will report an error ;reloadOnChange: If the configuration file is changed , The frame will reload

The configuration file ;

This profile Class is defined according to the field definition given in the configuration file , I won't post the definition of this class . The way of use is also the same as that described above FormatOptions equally . If there are other configuration items in this configuration file ,

Remember to call GetSection Method to get the part we want .

3、 Dynamically load the configuration file according to the running environment

stay ASP.NET CORE There is 3 Medium running environment :Development、Stage、Production. The contents of configuration files may be different in different environments .

Let's test the release environment . If the current project has not appsettings.Production.json file , Then build a new one .

The configuration is as follows :

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "format": {   
    "currencyDecimal": {
      "digits": "6"   
    }
  }
}
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            var formatConfig = new ConfigurationBuilder().AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile(path: $"appsettings.{environmentName}.json", optional: false, reloadOnChange: true).Build() ;
services.AddOptions().Configure<FormatOptions>(formatConfig.GetSection("format"));

You can see in appsettings.Production.json In profile , I didn't define FormatOptions All fields of , Only configuration CurrencyDecimalFormatOptions The inside of the class Digits Field .

Creating ConfigurationBuilder Class time , I added 2 individual appsettings.json, stay appsettings.json in , I defined FormatOptions All fields of .

stay appsettings.json Inside, I put Digits Set to 4, And in the appsettings.Production.json Inside, I put Digits Set to 6. And then in lanuchSettings.json Zhongba ASPNETCORE_ENVIRONMENT

Set to Production, Still TestController Run in , We found that Digits The value of the field is equal to 6.

I think this way is still very good , Write all configuration items in appsettings.json In file , Then write only the configuration items corresponding to the running environment in the configuration file corresponding to the running environment , There's no need to put all the

The configuration items are rewritten . The framework will merge the configuration items of the two files .

4、 Monitor changes in configuration files

We all hope to modify the configuration file during the running of the program without restarting the application , The modified configuration can also take effect ,ASP.NET CORE We did that .

The code is actually similar to the above , We want to monitor the changes of the configuration file , Only need to reloadOnChange Property is set to true that will do .

Then we're spending Options When the object , To use IOptionsMonitor, Not before IOptions, The code is as follows :

public TestController(IOptions<FormatOptions> options,IOptionsMonitor<FormatOptions> optionsMonitor)
        {
            _options = options;
            _monitorOptions = optionsMonitor;
        }

I added a new function :

public string MonitorIndex()
        {
            var value = _monitorOptions.CurrentValue;
            var dateTime = value.DateTime;
            var currencyDecimal = value.CurrencyDecimal;
            StringBuilder sb = new StringBuilder();
            sb.Append($"DateTime:");
            sb.Append($"\r\nlongDataPattern:{dateTime.LongDataPattern}");
            sb.Append($"\r\nlongTimePattern:{dateTime.LongTimePattern}");
            sb.Append($"\r\nshortDataPattern:{dateTime.ShortDataPattern}");
            sb.Append($"\r\nshortTimePattern:{dateTime.ShortTimePattern}");
            sb.Append($"\r\nCurrencyDecimal:");
            sb.Append($"\r\ndigits:{currencyDecimal.Digits}");
            sb.Append($"\r\nsymbol:{currencyDecimal.Symbol}");

            return sb.ToString();
        }

The only change is when you get the value CurrentValue attribute .

Enter... In the browser /test/MonitorIndex Enter the method , Then go to the root directory where the program runs (bin\Debug\netcoreapp3.1) Modify the value of any configuration item , preservation .

Then refresh , The interface will display the new value . If we still enter /test/index, It is found that the value of the modified configuration item will not change .

 

 

 

 

 

 

 

版权声明
本文为[begeneral]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230554081864.html