【APS.NET Core】- Json配置文件的读取
在项目目录下有个 appsettings.json ,我们先来操作这个文件。在appsettings.json中添加以下内容:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"FormatOptions": {
"DateTime": {
"LongDatePattern": "dddd, MMMM d, yyyy",
"LongTimePattern": "h:mm:ss tt",
"ShortDatePattern": "M/d/yyyy",
"ShortTimePattern": "h:mm tt"
},
"CurrencyDecimal": {
"Digits": 2,
"Symbol": "$"
}
}
}
现在我们的目的是读取红色部分的配置信息。
新建配置类
为了读取该文件,我们建立一个类:
public class FormatOptions
{
public DateTimeFormatOptions DateTime { get; set; }
public CurrencyDecimalFormatOptions CurrencyDecimal { get; set; } public FormatOptions(IConfiguration config)
{
this.DateTime = new DateTimeFormatOptions(config.GetSection("DateTime"));
this.CurrencyDecimal = new CurrencyDecimalFormatOptions(config.GetSection("CurrencyDecimal"));
} public class DateTimeFormatOptions
{
public string LongDatePattern { get; set; }
public string LongTimePattern { get; set; }
public string ShortDatePattern { get; set; }
public string ShortTimePattern { get; set; } //其他成员
public DateTimeFormatOptions(IConfiguration config)
{
this.LongDatePattern = config["LongDatePattern"];
this.LongTimePattern = config["LongTimePattern"];
this.ShortDatePattern = config["ShortDatePattern"];
this.ShortTimePattern = config["ShortTimePattern"];
}
} public class CurrencyDecimalFormatOptions
{
public int Digits { get; set; }
public string Symbol { get; set; } public CurrencyDecimalFormatOptions(IConfiguration config)
{
this.Digits = int.Parse(config["Digits"]);
this.Symbol = config["Symbol"];
}
}
}
字段与配置文件中一样。
在Startup中读取
在Startup的ConfigureServices方法中添加如下代码:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
}); //IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("").Build();
//services.Configure<KestrelServerOptions>(configuration); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddRazorPagesOptions(options=>
{
options.RootDirectory = "/Pages"; }); services.AddOptions();
services.Configure<FormatOptions>(Configuration.GetSection("FormatOptions"));
}
将配置文件的"FormatOptions"节点注册到类FormatOptions。借助于Options Pattern的自动绑定机制,我们无需逐条地读取配置,所以我们可以将这个三个Options类型(DateTimeFormatOptions、CurrencyDecimalOptions和FormatOptions)的构造函数全部删除,只保留其属性成员。变成:
public class FormatOptions
{
public DateTimeFormatOptions DateTime { get; set; }
public CurrencyDecimalFormatOptions CurrencyDecimal { get; set; } //public FormatOptions(IConfiguration config)
//{
// this.DateTime = new DateTimeFormatOptions(config.GetSection("DateTime"));
// this.CurrencyDecimal = new CurrencyDecimalFormatOptions(config.GetSection("CurrencyDecimal"));
//} public class DateTimeFormatOptions
{
public string LongDatePattern { get; set; }
public string LongTimePattern { get; set; }
public string ShortDatePattern { get; set; }
public string ShortTimePattern { get; set; } //其他成员
//public DateTimeFormatOptions(IConfiguration config)
//{
// this.LongDatePattern = config["LongDatePattern"];
// this.LongTimePattern = config["LongTimePattern"];
// this.ShortDatePattern = config["ShortDatePattern"];
// this.ShortTimePattern = config["ShortTimePattern"];
//}
} public class CurrencyDecimalFormatOptions
{
public int Digits { get; set; }
public string Symbol { get; set; } //public CurrencyDecimalFormatOptions(IConfiguration config)
//{
// this.Digits = int.Parse(config["Digits"]);
// this.Symbol = config["Symbol"];
//}
}
}
在PageModel中使用:
public class ContactModel : PageModel
{
public string Message { get; set; }
public FormatOptions Options { get; set; } public ContactModel(IOptions<FormatOptions> option)
{
this.Options = option.Value;
} public void OnGet()
{
Message = "Your contact page."; IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
this.Options = new ServiceCollection()
.AddOptions()
.Configure<FormatOptions>(config.GetSection("FormatOptions"))
.BuildServiceProvider()
.GetService<IOptions<FormatOptions>>()
.Value;
}
}
上述代码的绿色部分是另一种读取方式,这种方式直接使用构造函数的方式读取,而不是使用.net core的依赖注入。
类库中读取配置文件
为了统一管理配置文件的读取,我们大部分情况是需要在一个基础类库实现对配置文件的读取。所以封装了如下的类:
public class ConfigurationManager
{
public static T GetAppSettings<T>(string key) where T : class, new()
{
IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
return new ServiceCollection()
.AddOptions()
.Configure<T>(config.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<T>>()
.Value;
}
}
调用方法:
public class ContactModel : PageModel
{
public string Message { get; set; }
public FormatOptions Options { get; set; } public ContactModel(IOptions<FormatOptions> option)
{
//this.Options = option.Value;
this.Options = ConfigurationManager.GetAppSettings<FormatOptions>("Format");
} public void OnGet()
{
Message = "Your contact page.";
}
}
【APS.NET Core】- Json配置文件的读取的更多相关文章
- .Net Core Linux centos7行—.net core json 配置文件
.net core 对配置系统做出了大幅度更新,不在局限于之前的*.xml配置方式.现在支持json,xml,ini,in memory,环境变量等等.毫无疑问的是,现在的json配置文件是.net ...
- [.NET Core] 简单读取 json 配置文件
简单读取 json 配置文件 背景 目前发现网上的 .NET Core 读取配置文件有点麻烦,自己想搞个简单点的. .NET Core 已经不使用之前的诸如 app.config 和 web.conf ...
- Asp .Net Core 读取appsettings.json配置文件
Asp .Net Core 如何读取appsettings.json配置文件?最近也有学习到如何读取配置文件的,主要是通过 IConfiguration,以及在Program中初始化完成的. ...
- 【NET Core】.NET Core中读取json配置文件
在.NET Framework框架下应用配置内容一般都是写在Web.config或者App.config文件中,读取这两个配置文件只需要引用System.Configuration程序集,分别用 Sy ...
- .NET Core在类库中读取配置文件appsettings.json
在.NET Framework框架时代我们的应用配置内容一般都是写在Web.config或者App.config文件中,读取这两个配置文件只需要引用System.Configuration程序集,分别 ...
- .NET Core控制台利用【Options】读取Json配置文件
创建一个 .NET Core控制台程序 添加依赖 Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.FileE ...
- .Net Core控制台应用加载读取Json配置文件
⒈添加依赖 Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.FileExtensions Microsoft ...
- Asp.Net Core 3.1学习-读取、监听json配置文件(7)
1.前言 文件配置提供程序默认的给我们提供了ini.json.Xml等.都是读取不同格式的文件.文件配置提供程序支持文件可寻.必选.文件变更的监视. 2.读取配置文件 主要运用的包:需要Ini.xml ...
- .Net Core Web应用加载读取Json配置文件
⒈添加Json配置文件并将“复制到输出目录”属性设置为“始终复制” { "Logging": { "LogLevel": { "Default&quo ...
随机推荐
- 自添加LUCI菜单及编译为ipk
目录 添加汉化编译为ipk配置文件入口函数界面文件Makefile 添加 添加自己的luci界面,有3个必要的要素: a配置文件.新建一个在/etc/config/abcdefg b入口函数.新建一个 ...
- 第七篇:gcc和arm-linux-gcc常用选项
目录 一.gcc和arm-linux-gcc的常用选项 二.从.c文件到可执行文件过程 一.gcc和arm-linux-gcc的常用选项 常用选型 -v 查看gcc编译器的版本,显示gcc执行时的详细 ...
- P2P通讯
转载: http://www.cnblogs.com/pannengzhi/p/4800526.html http://blog.csdn.net/lee353086/article/details/ ...
- R语言爬虫:爬取百度百科词条
抓取目标:抓取花儿与少年的百度百科中成员信息 url <- "http://baike.baidu.com/item/%E8%8A%B1%E5%84%BF%E4%B8%8E%E5%B0 ...
- AS 3.1 项目打包成jar或aar
1.首先明白一个道理. Android Studio编译的时候会自动将项目生成jar和aar的,我一开始以为jar需要自己单独生成,其实AS已经自动生成了,网上找的很多资料都是一个复制的过程而已. 只 ...
- python中通过datetime获取UTC时间ISO格式
一个热点统计需求,需要限定一个时间范围,计算出该范围内的热点事件,相关数据则以UTC标准时间的ISO时间格式存在mongodb中,和服务器设置的时区UTC+8并不一致. 为了解决这个问题,直觉反应是在 ...
- LeetCode: 60. Permutation Sequence(Medium)
1. 原题链接 https://leetcode.com/problems/permutation-sequence/description/ 2. 题目要求 给出整数 n和 k ,k代表从1到n的整 ...
- 「日常训练」Known Notation(ZOJ-3829)
题意与分析 题意是这样的:给一个字符串,字符串中只包含数字和运算符'*'.现在问字符串是不是一个合法的逆波兰式(后缀表达式).已知逆波兰式的空格消除,也就是说123可以看成123也可以看成1和23.如 ...
- 搭建redis集群的过程中遇到的问题
1.GCC没有安装或版本不对 报错信息如下 CC adlist.o /bin/sh: cc: command not found make[1]: *** [adlist.o] Error 127 m ...
- TW实习日记:第28天
同前两天一样,等接口,开发,调试接口.重复地做着低级代码得搬运工作,确实挺没意思的.怪不得有些人一直说写低级代码很无聊,没有创造性和成就感.31号准备溜了,还是好好复习准备秋招吧. 挖坑清单: Vue ...