In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how to configure the Options option mode in ASP.NET Core". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope this article "how to configure the Options option mode in ASP.NET Core" can help you solve the problem.
1. Preface
The Options mode is an extension of the function of configuration (Configuration). In Chapter 12 (configuration II in ASP.NET Core) Configuration describes this feature (binding to an entity class, binding to an object graph, binding an array to a class) and the option mode has an option class (TOptions), which is used to associate attributes in the option class with keys in the configuration source. For example, suppose the json file has an option 1 key, and the option class also has a property name called Option1, which is configured so that the value of the key in the json can be mapped to the option class property value. It is also understandable that in a project application, a json file is serialized to a. Net class.
two。 General option configuration
The option class must be a non-abstract class that contains a public no-argument constructor. Add the configuration of option1, option2, and subsection to the appsettings.json file:
{"option1": "value1_from_json", "option2":-1, "subsection": {"suboption1": "subvalue1_from_json", "suboption2": 200}, "Logging": {"LogLevel": {"Default": "Warning"}, "AllowedHosts": "*"}
Create a new MyOptions class (Models/MyOptions.cs), and the following class MyOptions has three properties: Option1 and Option2. The default value is optional, but the class constructor in the following example sets the default value for Option1. Option2 has default values that are set by initializing properties directly:
Public class MyOptions {public MyOptions () {/ / Set default value. Option1 = "value1_from_ctor";} public string Option1 {get; set;} public int Option2 {get; set;} = 5;}
The MyOptions class is added to the service container through Configure and bound to the configuration:
Public void ConfigureServices (IServiceCollection services) {/ / Example # 1: General configuration / / Register the Configuration instance which MyOptions binds against. Services.Configure (Configuration);}
You can also use custom ConfigurationBuilder to load the option configuration from the settings file, confirm that the base path is set correctly, add it to the service container, and bind to the configuration:
Var configBuilder = new ConfigurationBuilder () .SetBasePath (Directory.GetCurrentDirectory ()) .AddJsonFile ("appsettings.json", optional: true); var config = configBuilder.Build (); services.Configure (config)
The following page model accesses the settings (Pages/Index.cshtml.cs) through IOptionsMonitor using constructor dependency injection:
Public class IndexModel {public IndexModel (IOptionsMonitor optionsAccessor) {_ options = optionsAccessor.CurrentValue;} private readonly MyOptions _ options; public void OnGet () {/ / Example # 1: Simple options var option1 = _ options.Option1; var option2 = _ options.Option2; var simpleOptions = $"option1 = {option1}, option2 = {option2}";}}
Call the IndexModel.OnGet method on the Home/Index controller Action to return a string containing the value of the option:
Public HomeController (IOptionsMonitor optionsAccessor) {_ optionsAccessor = optionsAccessor;} private readonly IOptionsMonitor _ optionsAccessor;public IActionResult Index () {IndexModel indexModel = new IndexModel (_ optionsAccessor); indexModel.OnGet (); return View ();}
3. Configure simple options by delegating
Use the delegate to set option values. This sample application uses the new MyOptionsWithDelegateConfig class (Models/MyOptionsWithDelegateConfig.cs):
Public class MyOptionsWithDelegateConfig {public MyOptionsWithDelegateConfig () {/ / Set default value. Option1 = "value1_from_ctor";} public string Option1 {get; set;} public int Option2 {get; set;} = 5;}
Add an IConfigureOptions service to the service container. It uses delegates through MyOptionsWithDelegateConfig to configure bindings:
Public void ConfigureServices (IServiceCollection services) {/ / Example # 2: Options bound and configured by a delegate services.Configure (myOptions = > {myOptions.Option1 = "value1_configured_by_delegate"; myOptions.Option2 = 500;});}
The following page model accesses the settings (Pages/Index.cshtml.cs) through IOptionsMonitor using constructor dependency injection:
Public class IndexModel {private readonly MyOptionsWithDelegateConfig _ optionsWithDelegateConfig; public IndexModel (IOptionsMonitor optionsAccessorWithDelegateConfig) {_ optionsWithDelegateConfig = optionsAccessorWithDelegateConfig.CurrentValue;} public void OnGet () {/ / Example # 2: Options configured by delegate var delegate_config_option1 = _ optionsWithDelegateConfig.Option1; var delegate_config_option2 = _ optionsWithDelegateConfig.Option2 Var simpleOptionsWithDelegateConfig = $"delegate_option1 = {delegate_config_option1}," + $"delegate_option2 = {delegate_config_option2}";}}
Call the IndexModel.OnGet method on the Home/Index controller Action to return a string containing the value of the option:
Public HomeController (IOptionsMonitor optionsAccessorWithDelegateConfig) {_ optionsAccessorWithDelegateConfig = optionsAccessorWithDelegateConfig;} private readonly IOptionsMonitor _ optionsAccessorWithDelegateConfig;public IActionResult Index () {IndexModel indexModel = new IndexModel (_ optionsAccessorWithDelegateConfig); indexModel.OnGet (); return View ();}
Each call to Configure adds the IConfigureOptions service to the service container. In the previous example, the values of Option1 and Option2 are both specified in appsettings.json, but the values of Option1 and Option2 are replaced by the configured delegate. When multiple configuration services are enabled, the last configuration source specified is superior to the other sources, which sets the configuration value. When you run the application, the OnGet method of the page model returns a string that displays the value of the option class.
4. Suboption configuration
When you bind an option to a configuration, each property in the option type is bound to the configuration key of the form property [: sub-property:]. For example, the MyOptions.Option1 property will bind to the key Option1 that is read from the option1 attribute in appsettings.json. In the following code, an IConfigureOptions service has been added to the service container. It binds MySubOptions to the subsection section of the appsettings.json file:
Public void ConfigureServices (IServiceCollection services) {/ / Example # 3: Suboptions / / Bind options using a sub-section of the appsettings.json file. Services.Configure (Configuration.GetSection ("subsection"));}
The new MySubOptions class (Models/MySubOptions.cs) defines the properties SubOption1 and SubOption2 to retain option values:
Public class MySubOptions {public MySubOptions () {/ / Set default values. SubOption1 = "value1_from_ctor"; SubOption2 = 5;} public string SubOption1 {get; set;} public int SubOption2 {get; set;}}
The following page model accesses the settings (Pages/Index.cshtml.cs) through IOptionsMonitor using constructor dependency injection:
Public class IndexModel {private readonly MySubOptions _ subOptions; public IndexModel (IOptionsMonitor subOptionsAccessor) {_ subOptions = subOptionsAccessor.CurrentValue;} public void OnGet () {/ / Example # 3: Suboptions var subOption1 = _ subOptions.SubOption1; var subOption2 = _ subOptions.SubOption2; var subOptions = $"subOption1 = {subOption1}, subOption2 = {subOption2}";}}
Call the IndexModel.OnGet method on the Home/Index controller Action to return a string containing the value of the option:
Public HomeController (IOptionsMonitor subOptionsAccessor) {_ subOptionsAccessor = subOptionsAccessor;} private readonly IOptionsMonitor _ subOptionsAccessor;public IActionResult Index () {IndexModel indexModel = new IndexModel (_ subOptionsAccessor); indexModel.OnGet (); return View ();}
5. Reload configuration data through IOptionsSnapshot
When IOptionsSnapshot accesses and caches options for the request lifecycle, the options can be evaluated only once per request. The following example shows how to create a new IOptionsSnapshot after changing the appsettings.json (Pages/Index.cshtml.cs). Multiple requests to the server return the configuration key values provided by the appsettings.json file before changing the appsettings.json file and reloading the configuration.
Public class IndexModel {private readonly MyOptions _ snapshotOptions; public IndexModel (IOptionsSnapshot snapshotOptionsAccessor) {_ snapshotOptions = snapshotOptionsAccessor.Value;} public void OnGet () {/ / Example # 5: Snapshot options var snapshotOption1 = _ snapshotOptions.Option1; var snapshotOption2 = _ snapshotOptions.Option2; var snapshotOptions = $"snapshot option1 = {snapshotOption1}," + $"snapshot option2 = {snapshotOption2}";}}
The initial option1 and option2 values loaded from the appsettings.json file are shown below:
Snapshot option1 = value1_from_json, snapshot option2 =-1
Change the values in the appsettings.json file to value1_from_json UPDATED and 200. Save the appsettings.json file. Refresh the browser to view the updated option values:
Snapshot option1 = value1_from_json UPDATED, snapshot option2 = 2006. Support for naming options that include IConfigureNamedOptions
Naming options support allows applications to distinguish between naming option configurations. The naming option is declared through OptionsServiceCollectionExtensions.Configure, which calls the extension method ConfigureNamedOptions.Configure:
Public void ConfigureServices (IServiceCollection services) {/ / Example # 6: Named options (named_options_1) / / Register the ConfigurationBuilder instance which MyOptions binds against. / / Specify that the options loaded from configuration are named / / "named_options_1". Services.Configure ("named_options_1", Configuration); / / Example # 6: Named options (named_options_2) / / Specify that the options loaded from the MyOptions class are named / / "named_options_2" / / Use a delegate to configure option values. Services.Configure ("named_options_2", myOptions = > {myOptions.Option1 = "named_options_2_value1_from_action";});}
Access naming options through OnGet (Pages/Index.cshtml.cs):
Public class IndexModel {private readonly MyOptions _ named_options_1; private readonly MyOptions _ named_options_2; public IndexModel (IOptionsSnapshot namedOptionsAccessor) {_ named_options_1 = namedOptionsAccessor.Get ("named_options_1"); _ named_options_2 = namedOptionsAccessor.Get ("named_options_2") } public void OnGet () {/ / Example # 6: Named options var named_options_1 = $"named_options_1: option1 = {_ named_options_1.Option1}," + $"option2 = {_ named_options_1.Option2}" Var named_options_2 = $"named_options_2: option1 = {_ named_options_2.Option1}," + $"option2 = {_ named_options_2.Option2}"; var namedOptions = $"{named_options_1} {named_options_2}";}}
Call the IndexModel.OnGet method on the Home/Index controller Action to return a string containing the value of the option:
Public HomeController (IOptionsSnapshot namedOptionsAccessor) {_ namedOptionsAccessor = namedOptionsAccessor;} private readonly IOptionsSnapshot _ namedOptionsAccessor;public IActionResult Index () {IndexModel indexModel = new IndexModel (_ namedOptionsAccessor); indexModel.OnGet (); return View ();}
Configure all options using the ConfigureAll method
Use the ConfigureAll method to configure all option instances. The following code configures Option1 for all configuration instances that contain common values. Manually add the following code to the Startup.ConfigureServices method:
Services.ConfigureAll (myOptions = > {myOptions.Option1 = "ConfigureAll replacement value";})
Call the IndexModel.OnGet method on the Home/Index controller Action to return a string containing the value of the option:
This is the end of the content about "how to configure the Options option mode in ASP.NET Core". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.