在项目目录下有个 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配置文件的读取的更多相关文章

  1. .Net Core Linux centos7行—.net core json 配置文件

    .net core 对配置系统做出了大幅度更新,不在局限于之前的*.xml配置方式.现在支持json,xml,ini,in memory,环境变量等等.毫无疑问的是,现在的json配置文件是.net ...

  2. [.NET Core] 简单读取 json 配置文件

    简单读取 json 配置文件 背景 目前发现网上的 .NET Core 读取配置文件有点麻烦,自己想搞个简单点的. .NET Core 已经不使用之前的诸如 app.config 和 web.conf ...

  3. Asp .Net Core 读取appsettings.json配置文件

         Asp .Net Core 如何读取appsettings.json配置文件?最近也有学习到如何读取配置文件的,主要是通过 IConfiguration,以及在Program中初始化完成的. ...

  4. 【NET Core】.NET Core中读取json配置文件

    在.NET Framework框架下应用配置内容一般都是写在Web.config或者App.config文件中,读取这两个配置文件只需要引用System.Configuration程序集,分别用 Sy ...

  5. .NET Core在类库中读取配置文件appsettings.json

    在.NET Framework框架时代我们的应用配置内容一般都是写在Web.config或者App.config文件中,读取这两个配置文件只需要引用System.Configuration程序集,分别 ...

  6. .NET Core控制台利用【Options】读取Json配置文件

    创建一个 .NET Core控制台程序 添加依赖 Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.FileE ...

  7. .Net Core控制台应用加载读取Json配置文件

    ⒈添加依赖 Microsoft.Extensions.Configuration Microsoft.Extensions.Configuration.FileExtensions Microsoft ...

  8. Asp.Net Core 3.1学习-读取、监听json配置文件(7)

    1.前言 文件配置提供程序默认的给我们提供了ini.json.Xml等.都是读取不同格式的文件.文件配置提供程序支持文件可寻.必选.文件变更的监视. 2.读取配置文件 主要运用的包:需要Ini.xml ...

  9. .Net Core Web应用加载读取Json配置文件

    ⒈添加Json配置文件并将“复制到输出目录”属性设置为“始终复制” { "Logging": { "LogLevel": { "Default&quo ...

随机推荐

  1. 用树莓派做电视盒子,安装Android TV系统

    有位朋友问我,如何在树莓派上安装盒子系统,这期我就教大家如何安装Android系统,自动动手做一个机顶盒. 如何安装系统,我已经在 树莓派安装系统 这篇文章中了做介绍,有需要的请看这篇文章.安装系统需 ...

  2. Python(1-8天总结)

    day1:变量:把程序运行过程中产生的中间值.暂时存储起来.方便后面的程序调用.变量命名规范:常量:所有字母大写注释:数据类型: 1. int 整数 2. str 字符串. 不会用字符串保存大量的数据 ...

  3. 利用RabbitMQ、MySQL实现超大用户级别的消息在/离线收发

    由于RabbitMQ中只有队列(queue)才能存储信息,所以用RabbitMQ实现超大用户级别(百万计)的消息在/离线收发需要对每一个用户创建一个永久队列. 但是RabbitMQ节点内存有限,经测试 ...

  4. 20145209刘一阳《网络对抗》实验五:MSF基础应用

    20145209刘一阳<网络对抗>实验五:MSF基础应用 主动攻击 首先,我们需要弄一个xp sp3 English系统的虚拟机,然后本次主动攻击就在我们kali和xp之间来完成. 然后我 ...

  5. 【BZOJ4818】序列计数(动态规划,生成函数)

    [BZOJ4818]序列计数(生成函数) 题面 BZOJ 题解 显然是求一个多项式的若干次方,并且是循环卷积 或者说他是一个\(dp\)也没有问题 发现项数很少,直接暴力乘就行了(\(FFT\)可能还 ...

  6. JavaScript---通过正则表达式验证表单输入

    验证输入的name只能是数字或字母或下划线 js <script type="text/javascript"> function submitOn(){ var f ...

  7. Ceres优化

    Ceres Solver是谷歌2010就开始用于解决优化问题的C++库,2014年开源.在Google地图,Tango项目,以及著名的SLAM系统OKVIS和Cartographer的优化模块中均使用 ...

  8. andriod学习一

    1.Android软件栈       2.Android模拟器        Android SDK 可以通过ADT+Eclipse或者命令行开发,调试,测试应用程序,设备可以使用模拟器或者真实设备, ...

  9. 「日常训练」Caterpillar(POJ-3310)

    题意与分析 一条很有趣的题目.给一个无向图,问它是否无环,且可以在上面找到一条线,使所有的顶点要么在线上要么不在线上但在与线相连的边上. 那么首先要确定所有点联系在一起.这个可以同判环一起处理:如果建 ...

  10. VIN码识别,车架号识别,OCR扫描工具

    近年二手车交易市场火爆,对二手车估值需要了详细解二手车的历史状况,车架号(VIN码)是车辆唯一的身份标识,也是了解二手车车况的入口,车商和二手车平台会频繁的进行车况查询,VIN码扫描识别技术给车辆估值 ...