Asp.net Core 和類庫讀取配置文件信息

Asp.net Core 和類庫讀取配置文件信息

看乾貨請移步至.net core 讀取配置文件公共類html

首先開一個腦洞,Asp.net core 被使用這麼長時間了,可是關於配置文件(json)的讀取,微軟官方彷佛並無給出像.net framework讀取web.config那樣簡單且完美。嚴重懷疑這是微軟爲了促進.net core 生態繁榮搞的一點小手段。web

appsetting.Development.json (appsetting.json的內容和這個差很少,下面會講到多環境使用)

{
  "SettingPath": {
    "VideoFilePath": "C:\\Users\\89275\\Desktop\\Projects\\mv",
    "FfmpegPath": "C:/Users/89275/Desktop/Projects/mv/ffmpeg.exe",
    "FtpPath": "http://192.168.254.1/videofile",
    "VirtualPath": "/videoplay"
  },
  "RedisPath":"192.168.0.108:6379"
}

看了不少Asp.net core 讀取配置文件的博客,感受都沒有很好的解決問題。

  1. 最簡單的就是在StartUp中經過Configuration["SettingPath:VirtualPath"]的形式獲取信息;
  2. 接下來就是在Controller中獲去配置文件信息,在控制器中讀取配置文件有兩種方法。
  • 第一種是在controller初始化的時候把IHostingEnvironment,IConfiguration傳過來,而後把穿過來的值賦給controller中對應的變量,酒後就能夠正常讀取配置文件了(因爲我是個菜逼,還沒看明白系統啓動的時候,這兩個變量是怎麼傳給controller的)
public class HomeController : Controller
    {
        //環境變量
        private readonly IHostingEnvironment hostingEnvironment;
        private IConfiguration Configuration;
        public HomeController(IHostingEnvironment hostingEnvironment, IConfiguration configuration)
        {
            this.hostingEnvironment = hostingEnvironment;
            Configuration = configuration;
        }

        pubilc void GetRedisPath()
        {
            string redisPath = Configuration["RedisPath"];
        }
    }
  • 第二種是經過獲取對象的方式讀取配置文件,最近不少博客說的都是關於這個的。仍是在controller初始化的時候把IOptions傳進來(這裏我仍是沒懂怎麼傳過來的/(ㄒoㄒ)/~~),而後把傳過來的值賦值給Model的對象,而後就能夠正常使用了。

這種方法須要在StartUp中的ConfigureServices中有添加redis

services.AddOptions();
            //SettingPath極爲Model
            services.Configure<SettingPath>(Configuration.GetSection("SettingPath"));
public class HomeController
    {

        public SettingPath settingPath;
        private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(VideosController));
        public HomeController(IOptions<SettingPath> option)
        {
            settingPath = option.Value;
        }

        public void GetVideoPath()
        {
            string path=SettingPath.VideoFilePath
        }
    }

這裏由於我不瞭解,IOptions是怎麼傳進來的,因此不知道若是有須要只用兩個或以上Model的狀況該怎麼處理。json

.net core 讀取配置文件公共類

前面幾種方法以前都有用過,可是我的感受用起來都不是很順手。並且若是想要在一個類庫中讀取配置文件的話簡直痛苦到不想理媳婦。app

因此本身動手寫了一個工具類asp.net

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System;

namespace Common
{
    public class ConfigurationHelper
    {
        public IConfiguration config { get; set; }
        public ConfigurationHelper()
        {
            IHostingEnvironment env = MyServiceProvider.ServiceProvider.GetRequiredService<IHostingEnvironment>();
            config = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();
        }
        public T GetAppSettings<T>(string key) where T : class, new()
        {
            var appconfig = new ServiceCollection()
                .AddOptions()
                .Configure<T>(config.GetSection(key))
                .BuildServiceProvider()
                .GetService<IOptions<T>>()
                .Value;
            return appconfig;
        }
    }
    //我比較喜歡單獨放這個類,可是這樣放更明顯
    public class MyServiceProvider
    {
        public static IServiceProvider ServiceProvider { get; set; }
    }
}

使用這個類的話須要在StartUp的Configure中添加ide

MyServiceProvider.ServiceProvider = app.ApplicationServices;

而後就能夠在任何地方使用此類讀取配置文件信息了,並且因爲ConfigurationHelper初始化時已經默認加載環境變量,因此同時具有多環境功能。工具

string path = new ConfigurationHelper().config["RedisPath"];
            SettingPath pathss = new ConfigurationHelper().GetAppSettings<SettingPath>("SettingPath");

參考ui

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/environments?view=aspnetcore-2.1
http://www.javashuo.com/article/p-bbrvuwkr-gu.htmlthis

相關文章
相關標籤/搜索