前言
首先開(kāi)一個(gè)腦洞,Asp.net core 被使用這么長(zhǎng)時(shí)間了,但是關(guān)于配置文件(json)的讀取,微軟官方似乎并沒(méi)有給出像.net framework讀取web.config那樣簡(jiǎn)單且完美。嚴(yán)重懷疑這是微軟為了促進(jìn).net core 生態(tài)繁榮搞的一點(diǎn)小手段。
appsetting.Development.json (appsetting.json的內(nèi)容和這個(gè)差不多,下面會(huì)講到多環(huán)境使用)
{ "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 讀取配置文件的博客,感覺(jué)都沒(méi)有很好的解決問(wèn)題。
第一種是在controller初始化的時(shí)候把IHostingEnvironment,IConfiguration傳過(guò)來(lái),然后把穿過(guò)來(lái)的值賦給controller中對(duì)應(yīng)的變量,酒后就可以正常讀取配置文件了(由于我是個(gè)菜逼,還沒(méi)看明白系統(tǒng)啟動(dòng)的時(shí)候,這兩個(gè)變量是怎么傳給controller的)
public class HomeController : Controller { //環(huán)境變量 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"]; } }第二種是通過(guò)獲取對(duì)象的方式讀取配置文件,最近很多博客說(shuō)的都是關(guān)于這個(gè)的。還是在controller初始化的時(shí)候把IOptions傳進(jìn)來(lái)(這里我還是沒(méi)懂怎么傳過(guò)來(lái)的/(ㄒoㄒ)/~~),然后把傳過(guò)來(lái)的值賦值給Model的對(duì)象,然后就可以正常使用了。
這種方法需要在StartUp中的ConfigureServices中有添加
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 } }這里因?yàn)槲也涣私猓琁Options是怎么傳進(jìn)來(lái)的,所以不知道如果有需要只用兩個(gè)或以上Model的情況該怎么處理。
.net core 讀取配置文件公共類
前面幾種方法之前都有用過(guò),但是個(gè)人感覺(jué)用起來(lái)都不是很順手。而且如果想要在一個(gè)類庫(kù)中讀取配置文件的話簡(jiǎn)直痛苦到不想理媳婦。
新聞熱點(diǎn)
疑難解答
圖片精選