前言
最近在研究把a(bǔ)sp.net程序移植到linux上,正好.net core出來(lái)了,就進(jìn)行了學(xué)習(xí)。
移植代碼基本順利,但是發(fā)現(xiàn).net core中沒(méi)有ConfigurationManager,無(wú)法讀寫(xiě)配置文件,單獨(dú)寫(xiě)個(gè)xml之類的嫌麻煩,就谷歌了下,發(fā)現(xiàn)了個(gè)方法,遂記錄如下,方便以后查找:
方法如下
配置文件結(jié)構(gòu)
public class DemoSettings { public string MainDomain { get; set; } public string SiteName { get; set; } }
appsettings.json中顯示效果
appsettings.json
{ "DemoSettings": { "MainDomain": "http://www.mysite.com", "SiteName": "My Main Site" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } }
配置Services
原配置
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); }
自定義
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); // Added - uses IOptions<T> for your settings. services.AddOptions(); // Added - Confirms that we have a home for our DemoSettings services.Configure<DemoSettings>(Configuration.GetSection("DemoSettings")); }
然后把設(shè)置注入進(jìn)相應(yīng)的Controller后就可以使用了
public class HomeController : Controller { private DemoSettings ConfigSettings { get; set; } public HomeController(IOptions<DemoSettings> settings) { ConfigSettings = settings.Value; } public IActionResult Index() { ViewData["SiteName"] = ConfigSettings.SiteName; return View(); } }
總結(jié)
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com