.net core 2x web项目中json配置文件的使用
2018-12-13 本文已影响10人
Angeladaddy
在.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
,建立文件

可以看到文件中自动添加了文件,并初始化了数据库连接字符串:
{
"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<AppSettings>(Configuration.GetSection("ApplicationSettings"));
services.AddMvc();
}
3. 使用配置信息
在任何一个Controller中,使用依赖注入拿到配置信息:
public class UserController : Controller
{
private readonly AppSettings _appSettings;
public UserController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
public IActionResult Login()
{
ViewBag.appName = _appSettings.ApplicationName;
return View();
}
}
我们把setting中的ApplicationName字段传到了前台:
//前端代码
<div class="login-logo">
<a href="http://fonour.cnblogs.com" target="_blank"><b>@ViewBag.appName</b></a>
</div>

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

【参考】