当前位置:网站首页>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
边栏推荐
- _ Mold_ Board_
- ◰GL-着色器处理程序封装
- JS, entries(), keys(), values(), some(), object Assign() traversal array usage
- ACL 2022 | dialogved: a pre trained implicit variable encoding decoding model for dialogue reply generation
- Go language RPC communication
- Zhongang Mining: Fluorite Flotation Process
- Nifi fast installation and file synchronization
- 【解决报错】Error in v-on handler: “TypeError: Cannot read property ‘resetFields’ of undefined”
- 1-2 JSX syntax rules
- 自定义my_strcpy与库strcpy【模拟实现字符串相关函数】
猜你喜欢

信息摘要、数字签名、数字证书、对称加密与非对称加密详解

ACL 2022 | dialogved: a pre trained implicit variable encoding decoding model for dialogue reply generation

Detailed explanation of information abstract, digital signature, digital certificate, symmetric encryption and asymmetric encryption

On lambda powertools typescript

线性代数感悟之2

VLAN advanced technology, VLAN aggregation, super VLAN, sub VLAN

网络安全之渗透靶场实战详解

Installing labellmg tutorial in Windows

Signalr can actively send data from the server to the client

Do you really understand the principle of code scanning login?
随机推荐
Promise (III)
JS, entries(), keys(), values(), some(), object Assign() traversal array usage
如何用Redis实现分布式锁?
vscode如何比较两个文件的异同
El cascade and El select click elsewhere to make the drop-down box disappear
Signalr can actively send data from the server to the client
BUG_ me
freeCodeCamp----prob_ Calculator exercise
Baidu Map 3D rotation and tilt angle adjustment
网络安全之渗透靶场实战详解
Promise (I)
Feign report 400 processing
1-2 JSX syntax rules
Tencent resolves the address according to the IP address
蓝桥杯省一之路06——第十二届省赛真题第二场
ASP. Net core reads the configuration file in the class library project
New keyword learning and summary
Document operation II (5000 word summary)
Get the column name list of the table quickly in Oracle
Zhongang Mining: Fluorite Flotation Process