This article mainly introduces the detailed ASP. NET core implementation of strongly typed configuration data, with a certain reference value, interested in small partners can refer to
Objective
Implement to read JSON file several ways, in the project to take the old way simple rough, the results of the boss came to see, well, it is not advisable, OK, I will use. NET core in the latest way Connaught, remember, the right is the best, do not lazy.
. NET core reads a JSON file by reading the file
When I open the VS2015 project with VS2017 and then add the controller, the error is as follows:
At this point we should add the following sentence in the. csproj of the project to resolve this issue:
<ItemGroup> <dotnetclitoolreference include= "Microsoft.VisualStudio.Web.CodeGeneration.Tools" version= " 1.0.0 "/> </ItemGroup>
We use the class to read the JSON directory IHostingEnvironment
and get the project directory through the following two properties in the class:
Gets the directory where the current project is located var contentpath = _hostingenv.contentrootpath; Get the directory where Wwwroot var rootpath = _hostingenv.webrootpath;
We create a folder with JSON under the current project, as follows:
In this JSON file, we give the following data:
{"Name": "Jeffcky", "Age": 25}
The next step is to read the JSON file and get the data:
[HttpPost] Public async task<iactionresult> Json () { var result = string. Empty; var FilePath = _hostingenv.contentrootpath + Path.directoryseparatorchar + "Json" + Path.directoryseparatorchar + " Read.json "; using (var StreamReader = System.IO.File.OpenText (FilePath)) { result = await streamreader.readtoendasync (); } var json = new {name = string. Empty, age = 0}; var data = Jsonconvert.deserializeanonymoustype (result, JSON); return View (); }
The data will be fully read at this time:
Until today I found that the anonymous type is read-only and cannot be assigned a value. "Ridiculous me."
The above is a way to read the JSON file by reading the data, when every request to read a file, not very appropriate, so the boss said it is not advisable, then use the second Connaught.
. NET core built-in read JSON file
What do we do when we need to get appsettings.json
the values in the other controllers? For example, we want to read the name value under the JB51 node of the JSON file
{"LogPath": "C:\\jeffcky_studyefcore\\logs", "Logging": {"Includescopes": false, "LogLevel": { "Default": "Debug" , "System": "Information", "Microsoft": "Information"}}, "jb51": {"name": "Jeffcky"}}
At this point we are reading by configuring the class configuration, and we need to inject such interfaces in two ways:
Services. Addsingleton<iconfigurationroot> (Configuration); Services. Addsingleton<iconfiguration> (Configuration);
The following is also obtained in the Controller constructor.
Then it gets the data under the Cnblogs node in the JSON.
This is a good way, but for us to get used to the smart hint if the wrong word, we have to check the trouble, so we finally read the JSON through a strong type to achieve. Loads our custom JSON file when the program starts.
Public Startup (ihostingenvironment env) { var builder = new Configurationbuilder () . Setbasepath (env. Contentrootpath) . Addjsonfile ("Appsettings.json", Optional:true, Reloadonchange:true) . Addjsonfile ($ "appsettings.{ Env. Environmentname}.json ", Optional:true) . Addjsonfile ("Read.json") . Addenvironmentvariables (); Configuration = Builder. Build (); }
Since a root node is required to read the configuration JSON, we will modify the above Read.json file as follows:
{"jb51": {"Name": "Jeffcky", "Age": 25}}
The node is then fetched in the ConfigureServices
method.
Services. Configure<person> (Configuration.getsection ("jb51"));
At this point the Controller constructor becomes the following:
Private readonly Models.person p; Public readjsoncontroller (ioptions<models.person> option) { p = option. Value; }
The data that is configured in the JSON will eventually be read directly:
[HttpPost] Public Iactionresult Json () { var = p.age; var name = P.name; return View (); }
Everything is so simple and natural.
Summarize
This section briefly explains how to implement a strongly typed configuration in. NET core so that when the program starts, it loads the JSON file directly into memory instead of reading the file every time, hoping for a bit of help in reading this article.
"Recommended"
1. asp free Video Tutorial
2. Eon the ASP Basic video tutorial
3. asp Tutorials