Explain in detail how asp.net core implements strong type configuration and reads configuration data

Time:2021-10-12

preface

There are several ways to read JSON files. The old method is simple and rough in the project. As a result, the boss came and looked. Well, this is not very desirable. All right, I’ll use the latest method in. Net core. Remember, what’s suitable is the best. Don’t be lazy.

. net core reads JSON files by reading files

When I open the vs2015 project with vs2017 and then add a controller, an error will be reported as follows:

At this time, we should add the following sentence to. Csproj in the project to solve this problem:


 <ItemGroup>
 <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
 </ItemGroup>

When we read the JSON directory, we useIHostingEnvironment Class to obtain the project directory through the following two properties in this class:

//Get the directory where the current project is located
   var contentPath = _hostingEnv.ContentRootPath;

   //Get the directory where wwwroot is located
   var rootPath = _hostingEnv.WebRootPath;

We create a folder for storing JSON under the current project, as follows:

In the JSON file, we give the following data:


{
 "name": "jeffcky",
 "age": 25
}

Next, 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 read completely:

Today, I found that anonymous types are read-only and cannot be assigned. [funny me]

The above method is to read the data by reading the JSON file. It is not appropriate to read the file once for each request, so the boss says it is not advisable, so use the second method.

. net core built-in read JSON file

When we need to get in other controllersappsettings.json What do we do when the value in? For example, we need to read the name value under the JSON file jb51 node


{
 "LogPath": "C:\\Jeffcky_StudyEFCore\\logs",
 "Logging": {
 "IncludeScopes": false,
 "LogLevel": {
  "Default": "Debug",
  "System": "Information",
  "Microsoft": "Information"
 }
 },
 "jb51": {
 "name": "Jeffcky"
 }
}

At this time, we read it by configuring the class configuration, and we need to inject this kind of interface. The following two methods can be used:


   services.AddSingleton<IConfigurationRoot>(Configuration);
   services.AddSingleton<IConfiguration>(Configuration);

Next, it is also obtained in the controller constructor.

Then you can get the data under the cnblogs node in the JSON.

This method is very good, but it’s not troublesome for us to get used to intelligent prompts. If we write the wrong word, we have to check it, so we finally read JSON and implement it through strong typing. Load 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 modify the above read.json file as follows:


{
 "jb51": {
 "Name": "jeffcky",
 "Age": 25
 }
}

Then inConfigureServices Method.


 services.Configure<Person>(Configuration.GetSection("jb51"));

At this point, the controller constructor becomes as follows:


  private readonly Models.Person p;
  public ReadJsonController(IOptions<Models.Person> option)
  {
   p = option.Value;
  }

Finally, the data configured in JSON will be read directly:


  [HttpPost]
  public IActionResult Json()
  {
   var age = p.Age;
   var name = p.Name;

   return View();
  }

Everything is so simple and natural.

summary

This section explains how to implement strongly typed configuration in. Net core, so that when the program starts, the JSON file can be directly loaded into memory instead of reading the file every time. I hope it will be of some help to you reading this article.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.