asp.net core 如何在Controller获取配置文件的值

场景:我们会把一些配置信息,写在配置文件文件中,便于我们修改和配置。在之前的asp.net 中可以通过ConfigurationManger来获取web.config里面的配置。在.net core 如何操作配置信息。

我们借助“Options Pattern” 的思想来解决在配置文件的获取。

我有一个配置文件appsetting.json内容如下:

{
  "ConnectionStrings": {
    "MySql": "Server=localhost;database=blog;uid=root;pwd=Password12!;"
  },
  "FileServers": [
    {
      "Host": "127.0.0.1",
      "Port": "5001"
    },
    {
      "Host": "127.0.0.1",
      "Port": "5002"
    }
  ],
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

现在要获取FileServers节点下面的信息,显然是一个数组或者集合,总之是多个值。

我们在项目的启动时候火读取appsetting.json文件的内容,此时,可以将我们需要的内容通过IOptions注入到容器中,当我们需要用到这些配置信息的时候再去容器里面获取:

直接上代码 在Startup里面中:

   // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            // services.AddOptions().Configure<FormatOptions>(Configuration.GetSection("Format"));
            ///using    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0"
            services.AddOptions().Configure<List<FileServerModel>>(Configuration.GetSection("FileServers"));
        }

在HomeController 里面 修改构造函数 获取IOptions里面的值:

  public List<FileServerModel> FileServers { set; get; }

        public HomeController(IOptions<List<FileServerModel>> options)
        {
            FileServers = options.Value;
        }

这样appsetting.json里面的值就可以获取到了。

 

posted @ 2017-01-05 23:39  nele  阅读(1108)  评论(0编辑  收藏  举报