前言
最近在研究把asp.net程序移植到linux上,正好.net core出來了,就進行了學習。
移植代碼基本順利,但是發現.net core中沒有ConfigurationManager,無法讀寫配置文件,單獨寫個xml之類的嫌麻煩,就谷歌了下,發現了個方法,遂記錄如下,方便以后查找:
方法如下
配置文件結構
1
2
3
4
5
|
public class DemoSettings { public string MainDomain { get ; set ; } public string SiteName { get ; set ; } } |
appsettings.json中顯示效果
appsettings.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
{ "DemoSettings": { "MainDomain": "http://www.mysite.com", "SiteName": "My Main Site" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "System": "Information", "Microsoft": "Information" } } } |
配置Services
原配置
1
2
3
4
5
|
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); } |
自定義
1
2
3
4
5
6
7
8
9
10
11
|
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" )); } |
然后把設置注入進相應的Controller后就可以使用了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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(); } } |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://metroset.me/?p=80