本系列目錄:ASP.NET MVC4入門到精通系列目錄匯總
刪除無用的視圖引擎
默認情況下,ASP.NET MVCE同時支持WebForm和Razor引擎,而我們通常在同一個項目中只用到了一種視圖引擎,如Razor,那么,我們就可以移除掉沒有使用的視圖引擎,提高View視圖的檢索效率。在沒有刪除WebForm引擎之前,檢索控制器中不存在的視圖時,我們可以從下圖看到,檢索視圖的順序是先Home目錄下面,然后Shared目錄下面的aspx、ascx文件。
1、在Global.asax中添加如下代碼:
void RemoveWebFormEngines() { var viewEngines = ViewEngines.Engines; var webFormEngines = viewEngines.OfType<WebFormViewEngine>().FirstOrDefault(); if (webFormEngines != null) { viewEngines.Remove(webFormEngines); } } protected void Application_Start() { RemoveWebFormEngines(); //移除WebForm視圖引擎 AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); }
現在再看下
壓縮合並Css和Js
在APS.NET MVC4中,App_Start文件夾下面多了一個BundleConfig.cs類,專門用於壓縮合並文件的,默認情況下壓縮合並功能是開啟的,當然我們也可以使用 BundleTable.EnableOptimizations = true;來顯示設置開啟。
但是,注意要在Web.config中將 調試設置為false,壓縮才會生效 <compilation debug="false" targetFramework="4.5" />
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery.min.js", "~/Scripts/jquery.easyui.min.js"));// "~/Scripts/jquery-{version}.js",
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/themes/default/easyui.css", "~/Content/themes/icon.css"));//"~/Content/site.css",
我們來看下壓縮合並前和壓縮合並后的對比
壓縮合並前:
壓縮合並后
很明顯,我們看到文件被合並了,減少了網絡請求數,同時,文件的大小也減小了,說明被壓縮處理了。
注意:我們只能合並同一類型的文件,也就是說不能把js和css文件合並到一起,只能單獨合並js文件和css文件。
使用防偽造令牌來避免CSRF攻擊
對表達提交來說,要關注的就是安全問題。ASP.NET MVC提供了探測某種攻擊類型的機制,其中一種措施就是防偽造令牌。這種令牌包含服務器端和客戶端組件,代碼會在表單中插入一個隱藏域以保存用戶特定的令牌 @Html.AntiForgeryToken()
@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@Html.AntiForgeryToken()
注意:@Html.AntiForgeryToken()只能添加在Html.BeginForm()形式申明的表單中,純HTML的<form>標簽表單是不行的。
Html.AntiForgeryToken輔助方法會寫入一個加密過的數據到用戶端瀏覽器的Cookie里,然后在表單內插入一個名為_RequestVerificationToken的隱藏字段,該隱藏字段的內容,每次刷新頁面都會不一樣,每次執行Action動作方法時,都會讓這個隱藏字段的值與Cookie的加密數據進行驗證比對,符合驗證才允許執行這個Action方法。
而且服務器端會優先在數據處理之前執行這些令牌驗證代碼,如下:[ValidateAntiForgeryToken]
[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Login(LoginModel model, string returnUrl) { if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)) { return RedirectToLocal(returnUrl); } // 如果我們進行到這一步時某個地方出錯,則重新顯示表單 ModelState.AddModelError("", "提供的用戶名或密碼不正確。"); return View(model); }
隱藏ASP.NET MVC版本
默認情況下,ASP.NET MVC網站會把版本號提供給瀏覽器,
在Global.asax中添加 MvcHandler.DisableMvcResponseHeader = true;
protected void Application_Start() { MvcHandler.DisableMvcResponseHeader = true; AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
判斷客戶端請求是否為Ajax:Request.IsAjaxRequest