Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How ASP.NET CORE reads json format configuration files

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how ASP.NET CORE reads json configuration files. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

In .net Framework, the configuration file is generally in XML format, .NET Framework provides a special ConfigurationManager to read the contents of the configuration file, and the json format configuration file is recommended in .net core, so how to read the json file in .net core?

First, read the json configuration file in the Startup class 1. Use Configuration to read directly.

Look at the following code:

Public IConfiguration Configuration {get;}

The Configuration property is provided in. Net core to read json files. For example:

Public void Configure (IApplicationBuilder app, IHostingEnvironment env) {string option1 = $"option1 = {this.Configuration [" Option1 "]}"; string option2 = $"option2 = {this.Configuration [" Option2 "]}"; string suboption1 = $"suboption1 = {this.Configuration [" subsection:suboption1 "]}"; / / read array string name1 = $"Name= {this.Configuration [" student:0:Name "]}" String age1 = $"Age= {this.Configuration [" student:0:Age "]}"; string name2 = $"Name= {this.Configuration [" student:1:Name "]}"; string age2 = $"Age= {this.Configuration [" student:1:Age "]}" / / output app.Run (c = > c.Response.WriteAsync (option1+ "\ r\ n" + option2+ "\ r\ n" + suboption1+ "\ r\ n" + name1+ "\ r\ n" + age1+ "\ r\ n" + name2+ "\ r\ n" + age2)); if (env.IsDevelopment ()) {app.UseDeveloperExceptionPage () } else {app.UseHsts ();} app.UseHttpsRedirection (); app.UseMvc ();}

Results:

2. Use IOptions interface 1, define entity class public class MongodbHostOptions {/ connection string / public string Connection {get; set;} / library / public string DataBase {get; set;} public string Table {get; set;}} 2, modify the json file

Add a MongodbHost node to the appsettings.json file:

{"Logging": {"LogLevel": {"Default": "Warning"}, "option1": "value1_from_json", "option2": 2, "subsection": {"suboption1": "subvalue1_from_json"}, "student": [{"Name": "Gandalf", "Age": "1000"}, {"Name": "Harry" "Age": "17"}], "AllowedHosts": "*", / / MongoDb "MongodbHost": {"Connection": "mongodb://127.0.0.1:27017", "DataBase": "TemplateDb", "Table": "CDATemplateInfo"}}

Note:

The attribute name in the MongodbHost must be the same as the attribute name in the defined entity class.

3. Configure in the StartUp class

Add OptionConfigure method binding

Private void OptionConfigure (IServiceCollection services) {/ / MongodbHost Information services.Configure (Configuration.GetSection ("MongodbHost"));}

Call the method defined above in the ConfigureServices method:

Public void ConfigureServices (IServiceCollection services) {/ / call the OptionConfigure method OptionConfigure (services); services.AddMvc () .SetCompatibilityVersion (CompatibilityVersion.Version_2_1);}

Used in the controller, the code is as follows:

Using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Options;namespace ReadJsonDemo.Controllers {[Route ("api/ [controller]")] [ApiController] public class MongodbController: ControllerBase {private readonly MongodbHostOptions _ mongodbHostOptions / public MongodbController (IOptions mongodbHostOptions) {_ mongodbHostOptions = mongodbHostOptions.Value;} [HttpGet] public async Task Get () {await Response.WriteAsync ("Connection:" + _ mongodbHostOptions.Connection + "\ r\ nDataBase) is injected through the constructor. "+ _ mongodbHostOptions.DataBase +"\ r\ nTable: "+ _ mongodbHostOptions.Table);}

Running result:

3. Read the custom json file

In the above example, we all read the appsettings.json file that comes with the system, so how do we read the json file that we define? You can use the ConfigurationBuilder class here.

Instantiation class var builder = new ConfigurationBuilder (); adding method 1builder.AddJsonFile ("path", false, true)

Where path represents the path to the json file, including the path and file name.

Add mode 2builder.Add (new JsonConfigurationSource {Path= "custom.json", Optional=false,ReloadOnChange=true}) .Build ()

The specific code is as follows:

Private void CustomOptionConfigure (IServiceCollection services) {IConfiguration _ configuration; var builder = new ConfigurationBuilder (); / / Mode 1 / / _ configuration = builder.AddJsonFile ("custom.json", false, true). Build (); / / Mode 2 _ configuration = builder.Add (new JsonConfigurationSource {Path= "custom.json", Optional=false,ReloadOnChange=true}). Build () Services.Configure (_ configuration.GetSection ("WebSiteConfig"));}

The ConfigureServices method is as follows:

Public void ConfigureServices (IServiceCollection services) {/ / call OptionConfigure method OptionConfigure (services); CustomOptionConfigure (services); services.AddMvc () .SetCompatibilityVersion (CompatibilityVersion.Version_2_1);}

The controller code is as follows:

Using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Options;namespace ReadJsonDemo.Controllers {[Route ("api/ [controller]")] [ApiController] public class MongodbController: ControllerBase {private readonly MongodbHostOptions _ mongodbHostOptions; private readonly WebSiteOptions _ webSiteOptions / public MongodbController (IOptions mongodbHostOptions,IOptions webSiteOptions) {_ mongodbHostOptions = mongodbHostOptions.Value; _ webSiteOptions = webSiteOptions.Value is injected through the constructor } [HttpGet] public async Task Get () {await Response.WriteAsync ("Connection:" + _ mongodbHostOptions.Connection + "\ r\ nDataBase;" + _ mongodbHostOptions.DataBase + "\ r\ nTable:" + _ mongodbHostOptions.Table); await Response.WriteAsync ("\ r\ n"); await Response.WriteAsync ("WebSiteName:" + _ webSiteOptions.WebSiteName + "\ r\ nWebSiteUrl;" + _ webSiteOptions.WebSiteUrl) Read the json file in the class library

In the above example, it is read directly in the application, so how do you read the json file in a separate class library? Look at the following sample code:

Using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Options;using System;using System.Collections.Generic;using System.IO;using System.Text;namespace Common {public class JsonConfigHelper {public static T GetAppSettings (string fileName, string key) where T: class, new () {/ / get the bin directory path var directory = AppContext.BaseDirectory; directory = directory.Replace ("\\", "/") Var filePath = $"{directory} / {fileName}"; if (! File.Exists (filePath)) {var length = directory.IndexOf ("/ bin"); filePath = $"{directory.Substring (0, length)} / {fileName}";} IConfiguration configuration; var builder = new ConfigurationBuilder () Builder.AddJsonFile (filePath, false, true); configuration = builder.Build (); var appconfig = new ServiceCollection () .AddOptions () .configure (configuration.GetSection (key)) .BuildServiceProvider () .GetService () .Value; return appconfig }}}

Note: the following assemblies should be added here, and it should be noted that the version of the added assembly should be the same as the assembly version in the. Net core web project, otherwise version conflicts will be reported.

1 、 Microsoft.Extensions.Configuration

2 、 Microsoft.Extensions.configuration.json

3 、 Microsoft.Extensions.Options

4 、 Microsoft.Extensions.Options.ConfigurationExtensions

5 、 Microsoft.Extensions.Options

The json file is as follows:

{"WebSiteConfig": {"WebSiteName": "CustomWebSite", "WebSiteUrl": "https:localhost:12345"}, "DbConfig": {"DataSource": "127.0.0.1", "InitialCatalog": "MyDb", "UserId": "sa", "Password": "123456"}}

The DbHostOptions entity class is defined as follows:

Using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace ReadJsonDemo {public class DbHostOptions {public string DataSource {get; set;} public string InitialCatalog {get; set;} public string UserId {get; set;} public string Password {get; set;}

Note: the DbHostOptions entity class here should be built in a separate class library, which is built directly in the application for demonstration purposes.

Call from the controller:

Using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Common;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Options;namespace ReadJsonDemo.Controllers {[Route ("api/ [controller]")] [ApiController] public class MongodbController: ControllerBase {private readonly MongodbHostOptions _ mongodbHostOptions; private readonly WebSiteOptions _ webSiteOptions / public MongodbController (IOptions mongodbHostOptions,IOptions webSiteOptions) {_ mongodbHostOptions = mongodbHostOptions.Value; _ webSiteOptions = webSiteOptions.Value is injected through the constructor } [HttpGet] public async Task Get () {DbHostOptions dbOptions = JsonConfigHelper.GetAppSettings ("custom.json", "DbConfig"); await Response.WriteAsync ("DataSource:" + dbOptions.DataSource + "\ r\ nInitialCatalog;" + dbOptions.InitialCatalog+ "\ r\ nUserId:" + dbOptions.UserId+ "\ r\ nPassword" + dbOptions.Password); await Response.WriteAsync ("\ r\ n") Await Response.WriteAsync ("Connection:" + _ mongodbHostOptions.Connection + "\ r\ nDataBase;" + _ mongodbHostOptions.DataBase + "\ r\ nTable:" + _ mongodbHostOptions.Table); await Response.WriteAsync ("\ r\ n"); await Response.WriteAsync ("WebSiteName:" + _ webSiteOptions.WebSiteName + "\ r\ nWebSiteUrl;" + _ webSiteOptions.WebSiteUrl);}

Running result:

On "ASP.NET CORE how to read json format configuration file" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report