一、基礎介紹
Global.asax 文件(也稱為 ASP.NET 應用程序文件)是一個可選文件,該文件包含響應 ASP.NET 或 HTTP 模塊所引發的應用程序級別和會話級別事件的代碼。
Application_Start是其中一個事件,在HttpApplication 類的第一個實例被創建時,該事件被觸發它允許你創建可以由所有HttpApplication 實例訪問的對象。
簡單來說,Application_Start()就是一個ASP.NET應用程序啟動時執行的方法,可以理解為應用程序入口。
二、代碼分析Application_Start()
1.出於安全考慮,去除X-AspNetMvc-Version頭
2.初始化上下文
3.判斷是否初始化數據庫
3.1 加載配置文件~/App_Data/Settings.txt
3.2 讀取內容,若存在連接字符串則說明已初始化數據庫
4.清空視圖引擎,添加自定義視圖引擎ThemeableRazorViewEngine,支持前台和后台頁面分離,及主題適配。
5.增加一些功能性的元數據
6.注冊常見的MVC物件,包括Area,Route
7.關閉MVC默認的標注特性Model驗證,添加FluentValidation(一種驗證組件)
8.啟動定時任務
8.1 初始化所有創建的定時任務
8.2 啟動定時任務線程
9.根據配置,是否啟動MiniProfiler(ASP.NET MVC的性能分析工具,監控網站性能)
9.1 安裝時默認為false,並配置在[dbo].[Setting]表,Name為storeinformationsettings.displayminiprofilerinpublicstore
9.2 配置方法
9.2.1 進入管理頁面,進入配置菜單
9.2.2 檢索storeinformationsettings.displayminiprofilerinpublicstore,定位該條目,修改Value值
9.2.3 啟動效果,在頁面左上角可看到該頁面執行時間,參考MiniProfiler相關資料
10.記錄應用啟動日志
10.1 通過依賴注入實例化
10.2 日志寫入數據庫,表[dbo].[Log]
11.代碼如下
1 protected void Application_Start() 2 { 3 //disable "X-AspNetMvc-Version" header name 4 MvcHandler.DisableMvcResponseHeader = true; 5 6 //initialize engine context 7 EngineContext.Initialize(false); 8 9 bool databaseInstalled = DataSettingsHelper.DatabaseIsInstalled(); 10 if (databaseInstalled) 11 { 12 //remove all view engines 13 ViewEngines.Engines.Clear(); 14 //except the themeable razor view engine we use 15 ViewEngines.Engines.Add(new ThemeableRazorViewEngine()); 16 } 17 18 //Add some functionality on top of the default ModelMetadataProvider 19 ModelMetadataProviders.Current = new NopMetadataProvider(); 20 21 //Registering some regular mvc stuff 22 AreaRegistration.RegisterAllAreas(); 23 RegisterRoutes(RouteTable.Routes); 24 25 //fluent validation 26 DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; 27 ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new NopValidatorFactory())); 28 29 //start scheduled tasks 30 if (databaseInstalled) 31 { 32 TaskManager.Instance.Initialize(); 33 TaskManager.Instance.Start(); 34 } 35 36 //miniprofiler 37 if (databaseInstalled) 38 { 39 if (EngineContext.Current.Resolve<StoreInformationSettings>().DisplayMiniProfilerInPublicStore) 40 { 41 GlobalFilters.Filters.Add(new ProfilingActionFilter()); 42 } 43 } 44 45 //log application start 46 if (databaseInstalled) 47 { 48 try 49 { 50 //log 51 var logger = EngineContext.Current.Resolve<ILogger>(); 52 logger.Information("Application started", null, null); 53 } 54 catch (Exception) 55 { 56 //don't throw new exception if occurs 57 } 58 } 59 }