標籤:
【無私分享:ASP.NET CORE 項目實戰】目錄索引
簡介
在我們之前的Asp.net mvc 開發中,一提到設定檔,我們不由的想到 web.config 和 app.config,在 core 中,我們看到了很多的變化,新的配置系統顯得更加輕量級,具有更好的擴充性,並且支援多樣化的資料來源。
部落格園對於這個的講解很多,比如:Artche ,但是,沒有點基礎看老A的部落格還是有些吃力的,對於老A介紹的配置,我也是看的一頭霧水,在後面的文章中,我會用像我們這些菜鳥容易接受的方式,重新解釋一下。
今天,我們以 appsettings.json 為例,讀取一些簡單的系統配置。
appsettings.json
在 第二章 中,我們在講到EF上線文時,在 Startup.cs 添加 services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection"))); 已經使用到了 appsettings.json
我們添加一些簡單的系統配置,來示範一下讀取 appsettings.json:
{
"ApplicationInsights": {
"InstrumentationKey": ""
},
"ConnectionStrings": {
"SqlServerConnection": "Server=.;Database=db_wkmvc;User ID=sa_wkmvc;Password=123456;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ApplicationConfiguration": {
//檔案上傳路徑
"FileUpPath": "/upload/",
//是否啟用單使用者登入
"IsSingleLogin": "True",
//允許上傳的檔案格式
"AttachExtension": "gif,jpg,jpeg,png,bmp,rar,zip,doc,docx,xls,xlsx,ppt,pptx,txt,flv,apk,mp4,mpg,ts,mpeg,mp3,bak,pdf",
//圖片上傳最大值KB
"AttachImagesize": 12400
}
}
我們添加一個配置類 ApplicationConfiguration
1 public class ApplicationConfiguration 2 { 3 #region 屬性成員 4 5 /// <summary> 6 /// 檔案上傳路徑 7 /// </summary> 8 public string FileUpPath { get; set; } 9 /// <summary>10 /// 是否啟用單使用者登入11 /// </summary>12 public bool IsSingleLogin { get; set; }13 /// <summary>14 /// 允許上傳的檔案格式15 /// </summary>16 public string AttachExtension { get; set; }17 /// <summary>18 /// 圖片上傳最大值KB19 /// </summary>20 public int AttachImagesize { get; set; }21 #endregion22 }
在 Startup.cs 的 ConfigureServices 添加
services.Configure<ApplicationConfiguration>(Configuration.GetSection("ApplicationConfiguration"));
添加一個領域層 AppConfigurtaionServices
public class AppConfigurtaionServices
{
private readonly IOptions<ApplicationConfiguration> _appConfiguration;
public AppConfigurtaionServices(IOptions<ApplicationConfiguration> appConfiguration)
{
_appConfiguration = appConfiguration;
}
public ApplicationConfiguration AppConfigurations
{
get
{
return _appConfiguration.Value;
}
}
}
添加引用 using Microsoft.Extensions.Options;
我們來測試一下:
測試結果:
希望跟大家一起學習Asp.net Core
剛開始接觸,水平有限,很多東西都是自己的理解和翻閱網上大神的資料,如果有不對的地方和不理解的地方,希望大家指正!
雖然Asp.net Core 現在很火熱,但是網上的很多資料都是前篇一律的複製,所以有很多問題我也暫時沒有解決,希望大家能共同協助一下!
【無私分享:ASP.NET CORE 項目實戰(第六章)】讀取設定檔(一) appsettings.json