netcore读取json文件_.net core 2x web项目中json配置文件的使用

在.net core 2x 版本中,可以从以下源获取配置(app configuration)信息:

Azure Key Vault

Command-line arguments

Custom providers (installed or created)

Directory files

Environment variables

In-memory .NET objects

Settings files

今天要说的是最后一种,从json配置文件中读取。

1. 首先建立appsettings.json配置文件

工程目录右键-搜索框中输入.json,建立文件

image.png

可以看到文件中自动添加了文件,并初始化了数据库连接字符串:

{

"DatabaseSettings": {

"ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"

}

}

再次重复这个过程,添加appsettings.Development.json和appsettings.Production.json文件。

{

"ApplicationSettings": {

"BaseUrl": "yourawesomewebsite.com",

"ApplicationName": "My Site",

"Version": "0.0.1",

"Enviroment": "Development"

}

}

{

"ApplicationSettings": {

"BaseUrl": "yourawesomewebsite.com",

"ApplicationName": "My Site",

"Version": "0.0.1",

"Enviroment": "Production"

}

}

两个文件的不同仅仅是Enviroment字段

2. 工程设置

在Startup.cs中添加构造函数:

public IConfiguration Configuration { get; set; }

public Startup(IHostingEnvironment env)

{

var builder = new ConfigurationBuilder()

.SetBasePath(env.ContentRootPath)

.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)

.AddEnvironmentVariables();

Configuration = builder.Build();

}

我们把所有的json文件都添加到了Configuration中,接下来,我们要建立一个AppSettings类,用来承载读取到的配置信息:

在工程文件夹下建立Models文件夹,建立一个类AppSettings.js

public class AppSettings

{

public string BaseUrl { get; set; }

public string ApplicationName { get; set; }

public string Version { get; set; }

public string Enviroment { get; set; }

}

和json文件的字段一一对应。

然后,在ConfigureServices方法中,添加ApplicationSettings字段:

public void ConfigureServices(IServiceCollection services)

{

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

services.AddMvc();

}

3. 使用配置信息

在任何一个Controller中,使用依赖注入拿到配置信息:

public class UserController : Controller

{

private readonly AppSettings _appSettings;

public UserController(IOptions appSettings)

{

_appSettings = appSettings.Value;

}

public IActionResult Login()

{

ViewBag.appName = _appSettings.ApplicationName;

return View();

}

}

我们把setting中的ApplicationName字段传到了前台:

//前端代码

image.png

任何时候,我们只要在工程启动参数中改变enviroment的值,就能改变工程参数设置,使用不同的json配置:

image.png

【参考】

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值