ASP. NET core implements strongly typed configuration data

Source: Internet
Author: User

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 ihostingenvironment class to read the JSON directory, and get the project directory through the following two properties in the class:

            // get 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"

The next step is to read the JSON file and get the data:

[HttpPost] Public AsyncTask<iactionresult>Json () {varresult =string.            Empty; varFilePath = _hostingenv.contentrootpath + Path.directoryseparatorchar +"Json"+ Path.directoryseparatorchar +"Read.json"; using(varStreamReader =System.IO.File.OpenText (FilePath)) {Result=awaitStreamreader.readtoendasync (); }            varJSON =New{name =string. Empty, age =0 }; vardata =Jsonconvert.deserializeanonymoustype (result, JSON); returnView (); }

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 the value of Appsettings.json in other controllers? For example, we want to read the name value under the Cnblogs node of the JSON file

{  "LogPath":"C:\\jeffcky_studyefcore\\logs",  "Logging": {    "Includescopes":false,    "LogLevel": {      "Default":"Debug",      "System":"Information",      "Microsoft":"Information"    }  },  "Cnblogs": {    "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.

         PublicStartup (ihostingenvironment env) {varBuilder =NewConfigurationbuilder (). 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:

{  "cnblogs": {    "Name""  jeffcky",    "age "   }}

The node is then fetched in the configureservices method.

Services. Configure<person> (Configuration.getsection ("cnblogs"));

At this point the Controller constructor becomes the following:

        Private ReadOnly Models.person p;          Public Readjsoncontroller (ioptions<models.person> option)        {            = option. Value;        }

The data that is configured in the JSON will eventually be read directly:

        [HttpPost]        public  iactionresult Json ()        {            var age = 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.

ASP. NET core implements strongly typed configuration data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.