In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to configure Configuration in ASP.NET Core". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to configure Configuration in ASP.NET Core.
1. Memory configuration
MemoryConfigurationProvider uses in-memory collections as configuration key-value pairs. To activate the in-memory collection configuration, call the AddInMemoryCollection extension method on the instance of ConfigurationBuilder. You can initialize the configuration provider using IEnumerable. Call ConfigureAppConfiguration when building the host to specify the configuration of the application:
Public class Program {public static readonly Dictionary _ dict = new Dictionary {{"MemoryCollectionKey1", "value1"}, {"MemoryCollectionKey2", "value2"}}; public static void Main (string [] args) {CreateWebHostBuilder (args) .Build () .Run () } public static IWebHostBuilder CreateWebHostBuilder (string [] args) = > WebHost.CreateDefaultBuilder (args) .Configuration ((hostingContext, config) = > {config.AddInMemoryCollection (_ dict);}) .UseStartup ();}
When you start the application, you will see the following configuration information:
1.1GetValue
ConfigurationBinder.GetValue extracts a value from the configuration with the specified key and can convert it to the specified type. If the key is not found, the configuration default value is obtained. As in the above example, two value1 and value2 values are configured. Now we extract the corresponding string values in the key MemoryCollectionKey1 configuration. If the configuration key MemoryCollectionKey1 cannot be found, the value3 configuration value is used by default. The sample code is as follows:
Public Startup (IConfiguration configuration) {Configuration = configuration; var config = Configuration.GetValue ("MemoryCollectionKey1", "value3");}
When you start the application, you will see the following configuration information:
ConfigurationBinder.GetValue finds the MemoryCollectionKey1 key value that defines the string type and outputs it. If we change the name of the get key to MemoryCollectionKey3, take a look at the output of the get key value:
We will see that when ConfigurationBinder.GetValue cannot find the key to define the string type MemoryCollectionKey3, the default value is output.
two。 Bind to an entity class
You can use option mode to bind a file configuration to a related entity class. The configuration value is returned as a string, but the POCO object can be bound by calling Bind. Bind is in the Microsoft.Extensions.Configuration.Binder package, and the latter is in the Microsoft.AspNetCore.App meta-package. Now we add a new file called starship.json in the CoreWeb/Models directory. The configuration content is as follows:
{"starship": {"name": "USS Enterprise", "registry": "NCC-1701", "class": "Constitution", "length": 304.8, "commissioned": false}, "trademark": "Paramount Pictures Corp. Http://www.paramount.com"}
Then add a physical model (/ Models/Starship.cs) corresponding to the configuration content:
Public class Starship {public string Name {get; set;} public string Registry {get; set;} public string Class {get; set;} public decimal Length {get; set;} public bool Commissioned {get; set;}}
Call ConfigureAppConfiguration when building the host to specify the configuration of the application:
Public static void Main (string [] args) {CreateWebHostBuilder (args). Build (). Run ();} public static IWebHostBuilder CreateWebHostBuilder (string [] args) = > WebHost.CreateDefaultBuilder (args) .ConfigreAppConfiguration ((hostingContext, config) = > {config.SetBasePath (Directory.GetCurrentDirectory ()); config.AddJsonFile ("starship.json", optional: true, reloadOnChange: true);}) .UseStartup ()
The sample application calls the GetSection method to get the starship key in the json file. Bind the starship key attribute value to an instance of the Starship class through the Bind method:
Var starship = new Starship (); Configuration.GetSection ("starship") .bind (starship); var _ starship = starship
The JSON file configuration content is provided when the application starts:
3. Bind to object graph
Through section 2, we learned how to bind configuration file contents to instantiated entity class properties, and similarly, configuration file contents can also be bound to object graphs. Now we add a new file called tvshow.xml in the CoreWeb/Models directory. The configuration content is as follows:
Dr. Who The Sun Makers 1126 1977 4 Tom Baker, Louise Jameson, John Leeson (c) 1977 BBC https://www.bbc.co.uk/programmes/b006q2x0
Then add an entity model (/ Models/TvShow.cs) corresponding to the configuration content, whose object graph contains Metadata and Actors classes:
Public class TvShow {public Metadata Metadata {get; set;} public Actors Actors {get; set;} public string Legal {get; set;}} public class Metadata {public string Series {get; set;} public string Title {get; set;} public DateTime AirDate {get; set;} public int Episodes {get; set;}} public class Actors {public string Names {get; set;}}
Call ConfigureAppConfiguration when building the host to specify the configuration of the application:
Config.AddXmlFile ("tvshow.xml", optional: true, reloadOnChange: true)
Use the Bind method to bind the configuration content to the entire TvShow object graph. Assign the binding instance to the property used for rendering:
Public Startup (IConfiguration configuration) {Configuration = configuration; var tvShow = new TvShow (); Configuration.GetSection ("tvshow") .bind (tvShow); var _ tvShow = tvShow;}
The XML file configuration content is provided when the application starts:
There is also a Bind method that binds the configuration content to the entire TvShow object graph:
Public Startup (IConfiguration configuration) {Configuration = configuration; var _ tvShow = Configuration.GetSection ("tvshow") .Get ();
The XML file configuration content is provided when the application starts:
4. Bind an array to a class
The Bind method also supports binding arrays in configuration content keys to object classes. Open the number key segment (: 0:,: 1:, … Any array format of: {n}:) can be bound to an array of POCO classes. Use the memory configuration provider to load these keys and values in the example:
Public class Program {public static Dictionary arrayDict = new Dictionary {{"array:entries:0", "value0"}, {"array:entries:1", "value1"}, {"array:entries:2", "value2"}, {"array:entries:4", "value4"} {"array:entries:5", "value5"}} Public static void Main (string [] args) {CreateWebHostBuilder (args). Build (). Run ();} public static IWebHostBuilder CreateWebHostBuilder (string [] args) = > WebHost.CreateDefaultBuilder (args) .ConfigreAppConfiguration ((hostingContext, config) = > {config.SetBasePath (Directory.GetCurrentDirectory ()); config.AddInMemoryCollection (arrayDict);}) .UseStartup () }
Because the configuration binder cannot bind null values, the array skips the value of index # 3. In the sample application, the POCO class can be used to hold the bound configuration data:
Public class ArrayExample {public string [] Entries {get; set;}}
Bind configuration data to an object:
Public Startup (IConfiguration configuration) {Configuration = configuration; var arrayExample = new ArrayExample (); Configuration.GetSection ("array") .bind (arrayExample); var _ arrayExample = arrayExample;}
You can also use the ConfigurationBinder.Get syntax to produce more concise code:
Public Startup (IConfiguration configuration) {Configuration = configuration; var _ arrayExample = _ config.GetSection ("array") .Get ();
The memory configuration is provided when the application starts:
5. Access the configuration in the Razor Pages page or MVC view
To access the configuration settings in the RazorPages page or MVC view, add the using directive (C# reference: using directive) to the Microsoft.Extensions.Configuration namespace and inject IConfiguration into the page or view.
In the Razor page:
@ page@model IndexModel@using Microsoft.Extensions.Configuration@inject IConfiguration Configuration Index Page Access configuration in a Razor Pages page
Configuration value for 'key': @ Configuration ["key"]
In the MVC view:
@ using Microsoft.Extensions.Configuration@inject IConfiguration Configuration Index View Access configuration in an MVC view
Configuration value for 'key': @ Configuration ["key"]
Thank you for reading, the above is the content of "how to configure Configuration in ASP.NET Core". After the study of this article, I believe you have a deeper understanding of how to configure Configuration in ASP.NET Core, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.