在项目目录下有个 appsettings.json ,我们先来操作这个文件。在appsettings.json中添加以下内容:

  1. {
  2. "Logging": {
  3. "LogLevel": {
  4. "Default": "Warning"
  5. }
  6. },
  7. "AllowedHosts": "*",
  8. "FormatOptions": {
  9. "DateTime": {
  10. "LongDatePattern": "dddd, MMMM d, yyyy",
  11. "LongTimePattern": "h:mm:ss tt",
  12. "ShortDatePattern": "M/d/yyyy",
  13. "ShortTimePattern": "h:mm tt"
  14. },
  15. "CurrencyDecimal": {
  16. "Digits": 2,
  17. "Symbol": "$"
  18. }
  19. }
  20. }

现在我们的目的是读取红色部分的配置信息。

新建配置类

为了读取该文件,我们建立一个类:

  1. public class FormatOptions
  2. {
  3. public DateTimeFormatOptions DateTime { get; set; }
  4. public CurrencyDecimalFormatOptions CurrencyDecimal { get; set; }
  5.  
  6. public FormatOptions(IConfiguration config)
  7. {
  8. this.DateTime = new DateTimeFormatOptions(config.GetSection("DateTime"));
  9. this.CurrencyDecimal = new CurrencyDecimalFormatOptions(config.GetSection("CurrencyDecimal"));
  10. }
  11.  
  12. public class DateTimeFormatOptions
  13. {
  14. public string LongDatePattern { get; set; }
  15. public string LongTimePattern { get; set; }
  16. public string ShortDatePattern { get; set; }
  17. public string ShortTimePattern { get; set; }
  18.  
  19. //其他成员
  20. public DateTimeFormatOptions(IConfiguration config)
  21. {
  22. this.LongDatePattern = config["LongDatePattern"];
  23. this.LongTimePattern = config["LongTimePattern"];
  24. this.ShortDatePattern = config["ShortDatePattern"];
  25. this.ShortTimePattern = config["ShortTimePattern"];
  26. }
  27. }
  28.  
  29. public class CurrencyDecimalFormatOptions
  30. {
  31. public int Digits { get; set; }
  32. public string Symbol { get; set; }
  33.  
  34. public CurrencyDecimalFormatOptions(IConfiguration config)
  35. {
  36. this.Digits = int.Parse(config["Digits"]);
  37. this.Symbol = config["Symbol"];
  38. }
  39. }
  40. }

字段与配置文件中一样。

在Startup中读取

在Startup的ConfigureServices方法中添加如下代码:

  1. // This method gets called by the runtime. Use this method to add services to the container.
  2. public void ConfigureServices(IServiceCollection services)
  3. {
  4. services.Configure<CookiePolicyOptions>(options =>
  5. {
  6. // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  7. options.CheckConsentNeeded = context => true;
  8. options.MinimumSameSitePolicy = SameSiteMode.None;
  9. });
  10.  
  11. //IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("").Build();
  12. //services.Configure<KestrelServerOptions>(configuration);
  13.  
  14. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddRazorPagesOptions(options=>
  15. {
  16. options.RootDirectory = "/Pages";
  17.  
  18. });
  19.  
  20. services.AddOptions();
  21. services.Configure<FormatOptions>(Configuration.GetSection("FormatOptions"));
  22. }

将配置文件的"FormatOptions"节点注册到类FormatOptions。借助于Options Pattern的自动绑定机制,我们无需逐条地读取配置,所以我们可以将这个三个Options类型(DateTimeFormatOptions、CurrencyDecimalOptions和FormatOptions)的构造函数全部删除,只保留其属性成员。变成:

  1. public class FormatOptions
  2. {
  3. public DateTimeFormatOptions DateTime { get; set; }
  4. public CurrencyDecimalFormatOptions CurrencyDecimal { get; set; }
  5.  
  6. //public FormatOptions(IConfiguration config)
  7. //{
  8. // this.DateTime = new DateTimeFormatOptions(config.GetSection("DateTime"));
  9. // this.CurrencyDecimal = new CurrencyDecimalFormatOptions(config.GetSection("CurrencyDecimal"));
  10. //}
  11.  
  12. public class DateTimeFormatOptions
  13. {
  14. public string LongDatePattern { get; set; }
  15. public string LongTimePattern { get; set; }
  16. public string ShortDatePattern { get; set; }
  17. public string ShortTimePattern { get; set; }
  18.  
  19. //其他成员
  20. //public DateTimeFormatOptions(IConfiguration config)
  21. //{
  22. // this.LongDatePattern = config["LongDatePattern"];
  23. // this.LongTimePattern = config["LongTimePattern"];
  24. // this.ShortDatePattern = config["ShortDatePattern"];
  25. // this.ShortTimePattern = config["ShortTimePattern"];
  26. //}
  27. }
  28.  
  29. public class CurrencyDecimalFormatOptions
  30. {
  31. public int Digits { get; set; }
  32. public string Symbol { get; set; }
  33.  
  34. //public CurrencyDecimalFormatOptions(IConfiguration config)
  35. //{
  36. // this.Digits = int.Parse(config["Digits"]);
  37. // this.Symbol = config["Symbol"];
  38. //}
  39. }
  40. }

在PageModel中使用:

  1. public class ContactModel : PageModel
  2. {
  3. public string Message { get; set; }
  4. public FormatOptions Options { get; set; }
  5. public ContactModel(IOptions<FormatOptions> option)
  6. {
  7. this.Options = option.Value;
  8. }
  9. public void OnGet()
  10. {
  11. Message = "Your contact page.";
  12.  
  13. IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
  14. this.Options = new ServiceCollection()
  15. .AddOptions()
  16. .Configure<FormatOptions>(config.GetSection("FormatOptions"))
  17. .BuildServiceProvider()
  18. .GetService<IOptions<FormatOptions>>()
  19. .Value;
  20. }
  21. }

上述代码的绿色部分是另一种读取方式,这种方式直接使用构造函数的方式读取,而不是使用.net core的依赖注入。

类库中读取配置文件

为了统一管理配置文件的读取,我们大部分情况是需要在一个基础类库实现对配置文件的读取。所以封装了如下的类:

  1. public class ConfigurationManager
  2. {
  3. public static T GetAppSettings<T>(string key) where T : class, new()
  4. {
  5. IConfiguration config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
  6. return new ServiceCollection()
  7. .AddOptions()
  8. .Configure<T>(config.GetSection(key))
  9. .BuildServiceProvider()
  10. .GetService<IOptions<T>>()
  11. .Value;
  12. }
  13. }

调用方法:

  1. public class ContactModel : PageModel
  2. {
  3. public string Message { get; set; }
  4. public FormatOptions Options { get; set; }
  5.  
  6. public ContactModel(IOptions<FormatOptions> option)
  7. {
  8. //this.Options = option.Value;
  9. this.Options = ConfigurationManager.GetAppSettings<FormatOptions>("Format");
  10. }
  11.  
  12. public void OnGet()
  13. {
  14. Message = "Your contact page.";
  15. }
  16. }

【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中的rabbitmq

    介绍 RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统.他遵循Mozilla Public License开源协议.MQ全称为Message Queue, 消息队列(MQ)是一种应用 ...

  2. C语言经典程序100例

    -------------------------------------------------------------------------------- [程序1] 题目:古典问题:有一对兔子 ...

  3. P2P通讯

    转载: http://www.cnblogs.com/pannengzhi/p/4800526.html http://blog.csdn.net/lee353086/article/details/ ...

  4. 使用java实现AES加密

    公司最近做agent项目,需要对一些远程重要的请求参数进行加密.加密之前选型,选择了AES,而DES算法加密,容易被破解.网上有很多关于加密的算法的Demo案列,我发现这些Demo在Window平台运 ...

  5. (数据科学学习手札43)Plotly基础内容介绍

    一.简介 Plotly是一个非常著名且强大的开源数据可视化框架,它通过构建基于浏览器显示的web形式的可交互图表来展示信息,可创建多达数十种精美的图表和地图,本文就将以jupyter notebook ...

  6. mybatis入门(二):增删改查

    mybatis的原理: 1.mybatis是一个持久层框架,是apache下的顶级项目 mybatis托管到googlecode下,目前托管到了github下面 2.mybatis可以将向prepar ...

  7. c#随机产生颜色

    有时为了满足现实的需要,我们想生成随机的较深的颜色,比如:彩色二维码,为了让手机.二维码识别设备可以正确识别,必须使用较深的颜色.如下图所示:        那么,如何实现呢?以下为源码: //C# ...

  8. 北京Uber优步司机奖励政策(1月17日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  9. JAVA面试中问及HIBERNATE与 MYBATIS的对比

    第一方面:开发速度的对比 就开发速度而言,Hibernate的真正掌握要比Mybatis来得难些.Mybatis框架相对简单很容易上手,但也相对简陋些.个人觉得要用好Mybatis还是首先要先理解好H ...

  10. memory引擎和innodb引擎速度对比

    ysql> insert into innodb_test (name) select name from innodb_test; Query OK, rows affected ( min ...