序言
在當前編程語言蓬勃發展與競爭的時期,對於我們.net從業者來說,.Net Core是風頭正緊,勢不可擋的.芸芸口水之中,不學習使用Core,你的圈內處境或許會漸漸的被邊緣化.所以我們還是抽出一點點時間學學.net core吧.
那VS Code 可以編寫,也可以調試Core本人也嘗試啦下,但是感覺扯淡的有點多,還是使用宇宙第一開發工具VS2017吧.
由於本篇是core的開篇,所以就稍微啰嗦一點,從創建web項目開始,先說項目文件,再來說一說配置文件與IOC使用.
創建web項目及項目文件簡介
關於web項目的創建,如果你創建不出來,自生自滅吧.點擊右上角的x,拜拜.

從上往下說這個目錄結構
1、launchSettings.json 啟動配置文件,文件默認內容如下.
{ "iisSettings": { //使用IIS Express啟動 "windowsAuthentication": false, //是否啟用windows身份驗證 "anonymousAuthentication": true, //是否啟用匿名身份驗證 "iisExpress": { "applicationUrl": "http://localhost:57566/", //訪問域名,端口 "sslPort": 0 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Production" //環境變量,默認為開發環境(Development),預發布環境(Staging),生產環境(Production) } }, "WebApplication1": { //選擇本地自宿主啟動,詳見Program.cs文件。刪除該節點也將導致Visual Studio啟動選項缺失 "commandName": "Project", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "http://localhost:57567" //本地自宿主端口 } } }
在vs的設計視圖中也可以編輯,如下圖,自己扣索下.

2、wwwroot和bower.json 靜態資源文件夾與引入靜態資源庫包版本配置文件,自己打開看下
3、依賴項,這個里面有4種吧,一種是bower前端資源庫,Nuget第三方,SDK,項目本身
4、Controllers,Views,這個不用介紹吧,mvc的2主.
5、appsettings.json :應用配置文件,類似於.net framework中的web.config文件
6、bundleconfig.json:打包壓縮配置文件
7、Program.cs:里面包含一個靜態Main文件,為程序運行的入口點
8、Startup.cs:這個默認為程序啟動的默認類.
這里的配置文件與2個入口類文件是萬物的根基,靈活多變,其中用我們值得學習了解的東西很多,這一章我不做闡述,后續章節再來補習功課,見諒,謹記.
.Net Core讀取配置文件
這個是我第一次入手學習core時候的疑問,我先是按照.Net Framework的方法來讀取配置文件,發現Core中根本沒有System.Configuration.dll.那怎么讀取配置文件呢?
那么如果要讀取配置文件中的數據,首先要加載Microsoft.Extensions.Configuration這個類庫.
首先看下我的默認配置文件,appsettings.json
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } } }
讀取他的第一種方式
/// <summary> /// 獲取配置節點對象 /// </summary> public static T GetSetting<T>(string key, string fileName = "appsettings.json") where T : class, new() { IConfiguration config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .Add(new JsonConfigurationSource { Path = fileName, Optional = false, ReloadOnChange = true }) .Build(); var appconfig = new ServiceCollection() .AddOptions() .Configure<T>(config.GetSection(key)) .BuildServiceProvider() .GetService<IOptions<T>>() .Value; return appconfig; }
public class Logging { public bool IncludeScopes { get; set; } public LogLevel LogLevel { get; set; } } public class LogLevel { public String Default { get; set; } }
var result =GetSetting<Logging>("Logging");
這樣即可,讀取到配置文件的內容,並填充配置文件對應的對象Logging.
如果你有自定義的節點,如下
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "Cad": { "a": false, "b": "18512312" } }
與上面一樣,首先定義對應的對象
public class Cad { public bool a { get; set; } public string b { get; set; } }
var result = GetSetting<Cad>("Cad");
有啦上面的方法很是簡單,還有一種情況是你想有自己的配置文件myconfig.json,那也很簡單,把上述方法的默認文件名改為myconfig.json即可!
除啦這個方法可以獲取配置文件外,core在mvc中還有另外獲取配置文件的方法,如下.
IOptions<Cad> cadConfig; public HomeController(IOptions<Cad> config) { cadConfig = config; } public IActionResult Index() { try { var result = cadConfig.Value; return View(result); } catch (Exception ex) { return View(ex); } }
就這樣,用法也很簡單.
但是如果配置文件中有的配置項需要你動態修改,怎么辦呢,用下面的方法試試.
/// <summary> /// 設置並獲取配置節點對象 /// </summary> public static T SetConfig<T>(string key, Action<T> action, string fileName = "appsettings.json") where T : class, new() { IConfiguration config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(fileName, optional: true, reloadOnChange: true) .Build(); var appconfig = new ServiceCollection() .AddOptions() .Configure<T>(config.GetSection(key)) .Configure<T>(action) .BuildServiceProvider() .GetService<IOptions<T>>() .Value; return appconfig; }
var c =SetConfig<Cad>("Cad", (p => p.b = "123"));
ok啦,自己試試吧,對配置文件的讀取,我這里目前只做到這里,后續有新的好方法再來分享.
.Net Core中運用IOC
當然在.net framework下能夠做依賴注入的第三方類庫很多,我們對此也了然於心,但是在core中無須引入第三放類庫即可做到.
public interface IAmount { string GetMyBanlance(); string GetMyAccountNo(); } public class AmountImp: IAmount { public string GetMyBanlance() { return "88.88"; } public string GetMyAccountNo() { return "CN0000000001"; } }
上面一個接口,一個實現,下面我們在Startup的ConfigureServices中把接口的具體實現注冊到ioc容器中.
public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddScoped<IAmount, AmountImp>(); // Add framework services. services.AddMvc(); } }
public class HomeController : Controller { IAmount amount; public HomeController(IAmount _amount) { amount = _amount; } public IActionResult Index() { try { var result = amount.GetMyAccountNo(); //結果為: "CN0000000001" return View(); } catch (Exception ex) { return View(ex); } }
}
這里呢,我只做一個簡單的示例,以供我們熟悉了解core,后續章節,如果運用的到會深入.
總結
入手.net core還是需要有很多新的認識點學習的,不是一兩篇博文可以涵蓋的,我們自己需要多總結思考學習.
這里我把一些的點,貼出來,希望對想入手core的同學有所幫助.如有志同道合者,歡迎加左上方群,一起學習進步.
