本系列目录:ASP.NET MVC4入门到精通系列目录汇总css
默认状况下,ASP.NET MVCE同时支持WebForm和Razor引擎,而咱们一般在同一个项目中只用到了一种视图引擎,如Razor,那么,咱们就能够移除掉没有使用的视图引擎,提升View视图的检索效率。在没有删除WebForm引擎以前,检索控制器中不存在的视图时,咱们能够从下图看到,检索视图的顺序是先Home目录下面,而后Shared目录下面的aspx、ascx文件。html
一、在Global.asax中添加以下代码:jquery
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(); }
如今再看下web
在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",
咱们来看下压缩合并前和压缩合并后的对比服务器
压缩合并前:网络
压缩合并后post
很明显,咱们看到文件被合并了,减小了网络请求数,同时,文件的大小也减少了,说明被压缩处理了。网站
注意:咱们只能合并同一类型的文件,也就是说不能把js和css文件合并到一块儿,只能单独合并js文件和css文件。
对表达提交来讲,要关注的就是安全问题。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网站会把版本号提供给浏览器,
在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