在项目目录下有个 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. python中如何退出多层循环

    1.定义标记变量:利用变量值的变化退出循环 # 第一种嵌套形式 a = [[1, 2, 3], [5, 5, 6], [7, 8, 9]] # init_i = 0 # init_j = 0 flag ...

  2. STM32(12)——CAN

    简介: CAN是Controller Area Network,是 ISO 国际标准化的串行通信协议. CAN  控制器根据两根线上的电位差来判断总线电平.总线电平分为显性电平和隐性电平,二者必居其一 ...

  3. Python(9-18天总结)

    day9:函数:def (形参): 函数体 函数名(实参)形参:在函数声明位置的变量 1. 位置参数 2. 默认值参数 3. 混合 位置, 默认值 4. 动态传参, *args 动态接收位置参数, * ...

  4. c语言指针的指针

    c语言在函数传递时常常使用如下的形式. void get(int **p) 对于这个形式,我想过为什么不能够使用 *p 作为形参呢.下面我们看一下代码和执行结果 void get(int **p) { ...

  5. (数据科学学习手札40)tensorflow实现LSTM时间序列预测

    一.简介 上一篇中我们较为详细地铺垫了关于RNN及其变种LSTM的一些基本知识,也提到了LSTM在时间序列预测上优越的性能,本篇就将对如何利用tensorflow,在实际时间序列预测任务中搭建模型来完 ...

  6. 修改注册表删除Windows资源管理器 “通过QQ发送” 右键菜单项

    运行regedit 展开至:HKEY_CLASSES_ROOT\AllFilesystemObjects\shellex\ContextMenuHandlers 删除QQShellExt项

  7. JavaScript’s “this”: how it works, where it can trip you up

    JavaScript’s “this”: how it works, where it can trip you up http://speakingjs.com/es5/ch23.html#_ind ...

  8. Solr第二讲——SolrJ客户端的使用与案例

    一.Solrj的使用 1.什么是Solrj solrj是访问Solr服务的java客户端(就像通过jedis操作redis一样),提供索引和搜索的请求方法,SolrJ通常在嵌入在业务系统中,通过Sol ...

  9. 20145226夏艺华 《Java程序设计》第1周学习总结

    http://www.cnblogs.com/bestixyh/p/5779286.html 去年暑假写的,确实比较丑陋,保留下来也是为了激励自己作出更多改变.寒假写的每一篇博客都尽最大努力养成了良好 ...

  10. HI-2110的657sp3版本应用笔记之TUP

    1. TUP是什么? TUP是华为的搞的一套封装了标准Coap的函数,底层是Coap,上层是华为封装的一层收发函数,用来简化Coap的收发流程,最终只用6个函数搞定,不用懂Coap就可以的. 2. T ...