asp.net mvc里的Filter真的是个很好的东西.之前看教程每次看到讲解Filter的地方总有模糊.今天在做测试项目的时候.管理员后台管理的时候.我在每个Action里都先验证了一下是否登录.结果做了7,8个Action的时候发现这样是不是有点太累了?脑袋里马上灵光一闪.Filter不是有个内置验证身份的吗?
马上搜索,一翻查找之后才发现内置的这个身份验证是争对membership的.而我使用的Forms验证..
咋办..继续搜呗.功夫不负有心人..终于让我给找到了.经过测试,使用很不错.
7,8个action里的if (!Request.IsAuthenticated)终于可以变成一句了..这样我就可以更安心的写Action了.
不说了.贴代码.
先是自定义的 Filter:
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; using System.Web.Routing; namespace cml.web.Filters { /// /// 角色认证 /// public class VaildateLoginRoleAttribute : ActionFilterAttribute { /// /// 角色名称 /// public string Role { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!string.IsNullOrEmpty(Role)) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { string redirectOnSuccess = filterContext.HttpContext.Request.RawUrl; string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess); string loginUrl = FormsAuthentication.LoginUrl + redirectUrl; filterContext.HttpContext.Response.Redirect(loginUrl, true); } else { //判断是否存在角色 FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; string roles = ticket.UserData; string[] chkRoles = this.Role.Split(','); bool isAuthorized = false; if (Array.IndexOf(chkRoles, roles) > -1) isAuthorized = true; else isAuthorized = false; if (!isAuthorized) filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "Manage", action = "AdminLogin" })); //throw new UnauthorizedAccessException("你没有权限访问该页面"); } } else { throw new InvalidOperationException("没有指定角色"); } } } //错误验证 //public class ErrorAttribute : ActionFilterAttribute //{ // public override void OnActionExecuted(ActionExecutedContext filterContext) // OnActionExecuted表示在Action执行之后 // { // if (filterContext.Exception != null) // { // filterContext.ExceptionHandled = true; // filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "Shared", action = "Error" })); // } // } //} public class VaildateLogin : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "Manage", action = "AdminLogin" })); } } } } FilterOK了..就去Controller里使用吧. [VaildateLogin] //这里就是使用的Filter验证,记得在using里引用Filter的命名空间. public ActionResult AddAdmin() { //if (!Request.IsAuthenticated) //这里是开始手动写的..多麻烦... //{ // return RedirectToAction("AdminLogin"); //} //else //{ cml.BLL.Admin bll = new cml.BLL.Admin(); ViewData["list_model"] = bll.GetAdminList("", 1); return View(); //} }
怎么样.很方便吧.如果是整个Controller下都需要身份验证的话..那就把这个Filter放到最外层的Controller上..这样就不用在每个Action上都写了.
完工..希望多点人来学习asp.net mvc..要不然教程太少了.好东西也太少了.