运维开发网

读取CORE的json格式配置文件

运维开发网 https://www.qedev.com 2022-07-16 22:53 出处:网络
<这篇文章介绍了ASP.NET?CORE读取json格式配置文件的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下


<这篇文章介绍了ASP.NET?CORE读取json格式配置文件的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

在。Net框架,配置文件通常是XML格式。的。NET Framework提供了一个特殊的ConfigurationManager来读取配置文件的内容。json格式的配置文件建议在。net核心,那么如何在。网芯?


一、在Startup类中读取json配置文件


1、使用Configuration直接读取

请看下面的代码:

public IConfiguration Configuration { get; }

配置属性在中提供。net核心来读取json文件。例如:

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"]}"; // 读取数组 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"]}"; // 输出 app.Run(c =gt; 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();}

结果:



2、使用IOptions接口


1、定义实体类public class MongodbHostOptions{ /// lt;summarygt; /// 连接字符串 /// lt;/summarygt; public string Connection { get; set; } /// lt;summarygt; /// 库 /// lt;/summarygt; public string DataBase { get; set; } public string Table { get; set; }}


2、修改json文件

在appsettings.json文件中添加MongodbHost节点:

{ "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" }}

注意:

MongodbHost中的属性名必须与定义的实体类中的属性名一致。


3、在StartUp类里面配置

添加选项配置方法绑定

private void OptionConfigure(IServiceCollection services){ //MongodbHost信息 services.Configurelt;MongodbHostOptionsgt;(Configuration.GetSection("MongodbHost"));}

调用上面在ConfigureServices方法中定义的方法:

public void ConfigureServices(IServiceCollection services){ // 调用OptionConfigure方法 OptionConfigure(services); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);}

在控制器中使用,代码如下:

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; /// lt;summarygt; /// 通过构造函数注入 /// lt;/summarygt; /// lt;param name="mongodbHostOptions"gt;lt;/paramgt; public MongodbController(IOptionslt;MongodbHostOptionsgt; mongodbHostOptions) { _mongodbHostOptions = mongodbHostOptions.Value; } [HttpGet] public async Task Get() { await Response.WriteAsync("Connection:" + _mongodbHostOptions.Connection + "\r\nDataBase;" + _mongodbHostOptions.DataBase + "\r\nTable:" + _mongodbHostOptions.Table); } }}

运行结果:



3、读取自定义json文件

在上面的例子中,我们读取的是系统自带的appsettings.json文件,那么如何读取自己定义的json文件呢?您可以在这里使用ConfigurationBuilder类。


实例化类var builder = new ConfigurationBuilder();


添加方式1builder.AddJsonFile("path", false, true);

其中path表示json文件的路径,包括路径和文件名。


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

具体代码如下:

private void CustomOptionConfigure(IServiceCollection services){ IConfiguration _configuration; var builder = new ConfigurationBuilder(); // 方式1 //_configuration = builder.AddJsonFile("custom.json", false, true).Build(); // 方式2 _configuration = builder.Add(new JsonConfigurationSource {Path= "custom.json",Optional=false,ReloadOnChange=true }).Build(); services.Configurelt;WebSiteOptionsgt;(_configuration.GetSection("WebSiteConfig"));}

配置方法如下:

public void ConfigureServices(IServiceCollection services){ // 调用OptionConfigure方法 OptionConfigure(services); CustomOptionConfigure(services); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);}

控制器代码如下:

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; /// lt;summarygt; /// 通过构造函数注入 /// lt;/summarygt; /// lt;param name="mongodbHostOptions"gt;lt;/paramgt; public MongodbController(IOptionslt;MongodbHostOptionsgt; mongodbHostOptions,IOptionslt;WebSiteOptionsgt; webSiteOptions) { _mongodbHostOptions = mongodbHostOptions.Value; _webSiteOptions = webSiteOptions.Value; } [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); } }}


二、在类库中读取json文件

上面的例子都是直接在应用中读取的,那么如何在单独的类库中读取json文件呢?请看下面的示例代码:

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 GetAppSettingslt;Tgt;(string fileName, string key) where T : class, new() { // 获取bin目录路径 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() .Configurelt;Tgt;(configuration.GetSection(key)) .BuildServiceProvider() .GetServicelt;IOptionslt;Tgt;gt;() .Value; return appconfig; } }}

注意:这里应该添加以下程序集,并且应该注意,添加的程序集的版本应该与。net核心web项目,否则会报错版本冲突。

1、Microsoft.Extensions.Configuration2、Microsoft.Extensions.configuration.json3、Microsoft.Extensions.Options4、Microsoft.Extensions.Options.ConfigurationExtensions5、Microsoft.Extensions.Options

Json文件如下:

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

DbHostOptions实体类定义如下:

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; } }}

注意:这里的DbHostOptions实体类应该是在单独的类库中构建的,为了演示方便,直接构建在应用程序中。

在控制器中调用:

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; /// lt;summarygt; /// 通过构造函数注入 /// lt;/summarygt; /// lt;param name="mongodbHostOptions"gt;lt;/paramgt; public MongodbController(IOptionslt;MongodbHostOptionsgt; mongodbHostOptions,IOptionslt;WebSiteOptionsgt; webSiteOptions) { _mongodbHostOptions = mongodbHostOptions.Value; _webSiteOptions = webSiteOptions.Value; } [HttpGet] public async Task Get() { DbHostOptions dbOptions = JsonConfigHelper.GetAppSettingslt;DbHostOptionsgt;("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); } }}

运行结果:


这就是这篇关于ASP.NET核心读取json格式配置文件的文章。/p>

0

精彩评论

暂无评论...
验证码 换一张
取 消