【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.";
        }
    }

 

posted @ 2018-10-24 15:44  wangwust  阅读(752)  评论(0编辑  收藏  举报