首頁  >  文章  >  後端開發  >  core Web中使用appsettings.json設定檔的實例詳解(ASP.NET )

core Web中使用appsettings.json設定檔的實例詳解(ASP.NET )

Y2J
Y2J原創
2017-04-27 10:11:223820瀏覽

這篇文章主要給大家介紹了在ASP.NET core Web中使用appsettings.json設定檔的方法,文中給了詳細的範例程式碼,需要的朋友可以參考學習,下面來一起看看吧。

前言

最近在研究把asp.net程式移植到linux上,剛好.net core出來了,就進行了學習。

移植程式碼基本上順利,但發現.net core中沒有ConfigurationManager,無法讀寫設定文件,單獨寫個xml之類的嫌麻煩,就谷歌了一下,發現了個方法,遂記錄如下,方便以後查找:

方法如下

#設定檔結構

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 for your settings.
 services.AddOptions();
 
 // Added - Confirms that we have a home for our DemoSettings
 services.Configure(Configuration.GetSection("DemoSettings"));
}

然後把設定注入進對應的Controller後就可以使用了

public class HomeController : Controller
{
 private DemoSettings ConfigSettings { get; set; }
 
 public HomeController(IOptions settings)
 {
  ConfigSettings = settings.Value;
 }
 
 public IActionResult Index()
 {
  ViewData["SiteName"] = ConfigSettings.SiteName;
  return View();
 }
}

總結

#

以上是core Web中使用appsettings.json設定檔的實例詳解(ASP.NET )的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn