您的位置:首页 > 编程语言 > ASP

ASP.NET Core开发-读取配置文件Configuration

2017-03-30 22:13 1226 查看
ASP.NET Core 是如何读取配置文件,今天我们来学习。

ASP.NET Core的配置系统已经和之前版本的ASP.NET有所不同了,之前是依赖于System.Configuration和XML配置文件web.config。

新的配置系统支持多种格式的配置文件。

下面我们来以json 格式的配置文件正式开始学习。

我们新建一个ASP.NET Core Web 应用程序,选择无身份验证。



读取配置文件

在项目目录下有个 appsettings.json ,我们先来操作这个文件。

在appsettings.json 添加如下两个节点。

{
"Data": "LineZero",
"ConnectionStrings": {
"DefaultConnection": "数据库1",
"DevConnection": "数据库2"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}


下面我们来读取。由于项目默认已经将该文件加入ConfigurationBuilder 之中,所以我们可以直接来读取。

在 Configure 方法中读取:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var data = Configuration["Data"];
//两种方式读取
var defaultcon = Configuration.GetConnectionString("DefaultConnection");
var devcon = Configuration["ConnectionStrings:DevConnection"];




调试程序,可以看到数据成功取出。

多环境区分

我们复制一个appsettings.json 然后重命名为 appsettings.Development.json

更改appsettings.Development.json 如下:

{
"Data": "LineZero Development",
"ConnectionStrings": {
"DefaultConnection": "开发数据库1",
"DevConnection": "开发数据库2"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}


然后我们调试程序,你会发现获取到的值变成了Development.json 里的值。



这里就是多环境配置。

public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)//增加环境配置文件,新建项目默认有
.AddEnvironmentVariables();
Configuration = builder.Build();
}


如果我们直接执行读取到的就是appsettings.json 的值,因为直接执行时是 Production 环境。

下面是输出图:

调试时:



dotnet run 时:



对象读取

我们在appsettings.json 及 Development.json 都添加一个 SiteConfig 节点。

"SiteConfig": {
"Name": "LineZero's Blog",
"Info": "ASP.NET Core 开发及跨平台,配置文件读取"
},


然后新建一个SiteConfig 类。

public class SiteConfig
{
public string Name { get; set; }
public string Info { get; set; }
}


首先在 ConfigureServices 中添加Options 及对应配置。

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
//添加options
services.AddOptions();
services.Configure<SiteConfig>(Configuration.GetSection("SiteConfig"));
}


然后我们在 Controller 中读取。

public class HomeController : Controller
{
public SiteConfig Config;

public HomeController(IOptions<SiteConfig> option)
{
Config = option.Value;
}

public IActionResult Index()
{
return View(Config);
}
}


对应View Index.cshtml

@model SiteConfig
@{
ViewData["Title"] = Model.Name;
}
<h1>@Model.Name</h1>
<h2>@Model.Info</h2>


执行程序 http://localhost:5000/


如果你觉得本文对你有帮助,请点击“推荐”,谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐