首页 > Web开发 > 详细

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

时间:2017-01-06 01:19:27      阅读:1438      评论:0      收藏:0      [点我收藏+]

场景:我们会把一些配置信息,写在配置文件文件中,便于我们修改和配置。在之前的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里面的值就可以获取到了。

 

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

原文:http://www.cnblogs.com/nele/p/6254463.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!