netcore读取json文件_.net core读取json格式的配置文件

在.Net Framework中,配置文件一般采用的是XML格式的,.NET Framework提供了专门的ConfigurationManager来读取配置文件的内容,.net core中推荐使用json格式的配置文件,那么在.net core中该如何读取json文件呢?

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

1、使用Configuration直接读取

看下面的代码:

public IConfiguration Configuration { get; }

Configuration属性就是.net core中提供的用来读取json文件。例如:

public voidConfigure(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 => 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 classMongodbHostOptions

{///

///连接字符串///

public string Connection { get; set; }///

///库///

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类里面配置

添加OptionConfigure方法绑定

private voidOptionConfigure(IServiceCollection services)

{//MongodbHost信息

services.Configure(Configuration.GetSection("MongodbHost"));

}

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

public voidConfigureServices(IServiceCollection services)

{//调用OptionConfigure方法

OptionConfigure(services);

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

}

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

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.Extensions.Options;namespaceReadJsonDemo.Controllers

{

[Route("api/[controller]")]

[ApiController]public classMongodbController : ControllerBase

{private readonlyMongodbHostOptions _mongodbHostOptions;///

///通过构造函数注入///

///

public MongodbController(IOptionsmongodbHostOptions)

{

_mongodbHostOptions=mongodbHostOptions.Value;

}

[HttpGet]public asyncTask 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();

添加方式1

builder.AddJsonFile("path", false, true);

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

添加方式2

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

具体代码如下:

private voidCustomOptionConfigure(IServiceCollection services)

{

IConfiguration _configuration;var builder = newConfigurationBuilder();//方式1//_configuration = builder.AddJsonFile("custom.json", false, true).Build();//方式2

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

services.Configure(_configuration.GetSection("WebSiteConfig"));

}

ConfigureServices方法如下:

public voidConfigureServices(IServiceCollection services)

{//调用OptionConfigure方法

OptionConfigure(services);

CustomOptionConfigure(services);

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

}

控制器代码如下:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.Extensions.Options;namespaceReadJsonDemo.Controllers

{

[Route("api/[controller]")]

[ApiController]public classMongodbController : ControllerBase

{private readonlyMongodbHostOptions _mongodbHostOptions;private readonlyWebSiteOptions _webSiteOptions;///

///通过构造函数注入///

///

public MongodbController(IOptions mongodbHostOptions,IOptionswebSiteOptions)

{

_mongodbHostOptions=mongodbHostOptions.Value;

_webSiteOptions=webSiteOptions.Value;

}

[HttpGet]public asyncTask 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文件呢?看下面的示例代码:

usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.Extensions.Options;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Text;namespaceCommon

{public classJsonConfigHelper

{public static T GetAppSettings(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 = newConfigurationBuilder();

builder.AddJsonFile(filePath,false, true);

configuration=builder.Build();var appconfig = newServiceCollection()

.AddOptions()

.Configure(configuration.GetSection(key))

.BuildServiceProvider()

.GetService>()

.Value;returnappconfig;

}

}

}

注意:这里要添加如下几个程序集,并且要注意添加的程序集的版本要和.net core web项目里面的程序集版本一致,否则会报版本冲突的错误

1、Microsoft.Extensions.Configuration

2、Microsoft.Extensions.configuration.json

3、Microsoft.Extensions.Options

4、Microsoft.Extensions.Options.ConfigurationExtensions

5、Microsoft.Extensions.Options

json文件如下:

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

}

DbHostOptions实体类定义如下:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;namespaceReadJsonDemo

{public classDbHostOptions

{public string DataSource { get; set; }public string InitialCatalog { get; set; }public string UserId { get; set; }public string Password { get; set; }

}

}

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

在控制器中调用:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingCommon;usingMicrosoft.AspNetCore.Http;usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.Extensions.Options;namespaceReadJsonDemo.Controllers

{

[Route("api/[controller]")]

[ApiController]public classMongodbController : ControllerBase

{private readonlyMongodbHostOptions _mongodbHostOptions;private readonlyWebSiteOptions _webSiteOptions;///

///通过构造函数注入///

///

public MongodbController(IOptions mongodbHostOptions,IOptionswebSiteOptions)

{

_mongodbHostOptions=mongodbHostOptions.Value;

_webSiteOptions=webSiteOptions.Value;

}

[HttpGet]public asyncTask 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);

}

}

}

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值