ASP.NET MVC 在搜尋 View 檔案時,會依照指定的順序搜尋,我們可以將不必要的項目移除來減少 I/O 的負擔。
當 View 檔案不存在時,會看到以下錯誤訊息,其實就是 View Engine 搜尋的順序,而這個順序是可以自訂的。
找不到檢視 ‘Index’ 或其主版,或沒有任何檢視引擎支援搜尋的位置。已搜尋過下列位置:
~/Views/Home/Index.aspx
~/Views/Home/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
移除不使用的 View Engine
ASP.NET MVC 預設註冊了 WebForm View Engine 及 Razor View Engine 這兩個 View Engine,我們可以將不需要的移除,藉由調整 ViewEngines.Engines 集合即可。
在 ~/App_Start/ 資料夾新增 ViewEngineConfig.cs。
1 2 3 4 5 6 7 8 9 10
| public class ViewEngineConfig { public static void RegisterViewEngines(ViewEngineCollection viewEngines) { viewEngines.Clear(); viewEngines.Add(new RazorViewEngine()); } }
|
修改 Global.asax 的 Application_Start 方法,在應用程式啟動時調整 ViewEngine 集合。
1 2 3 4 5 6 7 8 9 10
| public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { ViewEngineConfig.RegisterViewEngines(ViewEngines.Engines); } }
|
完成之後將不會再搜尋副檔名為 .aspx 的 View 檔案。
調整 View Engine 的 View 檔案搜尋順序
假設在上一步驟只保留 RazorViewEngine,Razor View Engine 預設會搜尋副檔名為 .cshtml 及 .vbhtml 的 view 檔案,但如果我們只是用 C# 開發,可以將 .vbhtml 移除,或使用 VB.NET 則可以將 .cshtml 移除。
將程式碼寫在上一個步驟的 ViewEngineConfig.cs,作法是自訂一個繼承自 RazorViewEngine 的類別,並自訂自己的搜尋路徑,在這裡是將 .vbhtml 路徑都移除。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| public class ViewEngineConfig { public static void RegisterViewEngines(ViewEngineCollection viewEngines) { viewEngines.Clear(); viewEngines.Add(new CSharpRazorViewEngine()); } internal class CSharpRazorViewEngine : RazorViewEngine { public CSharpRazorViewEngine() { AreaViewLocationFormats = new[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml" }; AreaMasterLocationFormats = new[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml" }; AreaPartialViewLocationFormats = new[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml" }; ViewLocationFormats = new[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml" }; MasterLocationFormats = new[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml", }; PartialViewLocationFormats = new[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml" }; FileExtensions = new[] { "cshtml" }; } } }
|
完成之後變成只搜尋兩個地方。
找不到檢視 ‘Index’ 或其主版,或沒有任何檢視引擎支援搜尋的位置。已搜尋過下列位置:
~/Views/Home/Index.cshtml
~/Views/Shared/Index.cshtml