MVC利用过滤器实现登录验证

mvc的知识过滤器可以自己查找,这里只是简单demo。

新建项目,添加引用首先新建4.5框架的web应用空程序。创建好后,进入包控制台,执行命令来添加两个关键引用:

install-package microsoft.aspnet.mvc.zh-hansinstall-package microsoft.aspnet.Web.Optimization.zh-hans


项目结构如图


在global.asax文件种配置一个路由用于请求。

<code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; using System.Web.Mvc; using System.Web.Routing; namespace LoginAttributeDemo { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { RouteTable.Routes.MapRoute(name:"default",url:"{controller}/{action}"); } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }/<code>

创建自定义校验过滤器LoginCheckFilter

<code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace LoginAttributeDemo { public class LoginCheckFilter : FilterAttribute,IAuthorizationFilter { public bool IsCheck { get; set; } public LoginCheckFilter(bool ischeck=false) { IsCheck = ischeck; } public void OnAuthorization(AuthorizationContext filterContext) { if (IsCheck) { var cookie = HttpContext.Current.Request.Cookies["user"]; if(cookie==null) { HttpContext.Current.Response.Write("失败"); // 结束当前请求 HttpContext.Current.Response.End(); } } } } }/<code>

主要就是继承了一个类和接口,IAuthorizationFilter的方法会在进入控制器或其方法时执行,这样就达到了过滤器的作用。
创建控制器

<code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace LoginAttributeDemo { public class UserController:Controller { [LoginCheckFilter(true)] public ActionResult Index() { return Content("成功"); } } }/<code>

当LoginCheckFilter传入为true时才进行校验。允许,浏览器请求user/index,发现成功被拦截了。


刷新页面,因为有了cookie通过了校验,成功访问了action