话说来到上海已经快半年了,时光如白驹过隙,稍微不注意,时间就溜走了,倒是没有那么忙碌,闲暇之际来博客园还是比较多的,记得上次在逛博问的时候看到有同志在问MVC中Cookie过期后如何作相关处理,他在阐述那么多页面不可能都去一个个手动处理。其实MVC很牛逼的地方就是把Attribute利用的非常完美,接下来就来看下它是如何做到的吧!
第一步、我们要定义一个登录过滤标签-LoginFilterAttribute并且继承AuthorizeAttribute。来看下它内部是啥样子
1 // Summary: 2 // Represents an attribute that is used to restrict access by callers to an 3 // action method. 4 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 5 public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter 6 { 7 // Summary: 8 // Initializes a new instance of the System.Web.Mvc.AuthorizeAttribute class. 9 public AuthorizeAttribute();10 11 // Summary:12 // Gets or sets the user roles.13 //14 // Returns:15 // The user roles.16 public string Roles { get; set; }17 //18 // Summary:19 // Gets the unique identifier for this attribute.20 //21 // Returns:22 // The unique identifier for this attribute.23 public override object TypeId { get; }24 //25 // Summary:26 // Gets or sets the authorized users.27 //28 // Returns:29 // The authorized users.30 public string Users { get; set; }31 32 // Summary:33 // When overridden, provides an entry point for custom authorization checks.34 //35 // Parameters:36 // httpContext:37 // The HTTP context, which encapsulates all HTTP-specific information about38 // an individual HTTP request.39 //40 // Returns:41 // true if the user is authorized; otherwise, false.42 //43 // Exceptions:44 // System.ArgumentNullException:45 // The httpContext parameter is null.46 protected virtual bool AuthorizeCore(HttpContextBase httpContext);47 //48 // Summary:49 // Processes HTTP requests that fail authorization.50 //51 // Parameters:52 // filterContext:53 // Encapsulates the information for using System.Web.Mvc.AuthorizeAttribute.54 // The filterContext object contains the controller, HTTP context, request context,55 // action result, and route data.56 protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);57 //58 // Summary:59 // Called when a process requests authorization.60 //61 // Parameters:62 // filterContext:63 // The filter context, which encapsulates information for using System.Web.Mvc.AuthorizeAttribute.64 //65 // Exceptions:66 // System.ArgumentNullException:67 // The filterContext parameter is null.68 public virtual void OnAuthorization(AuthorizationContext filterContext);69 //70 // Summary:71 // Called when the caching module requests authorization.72 //73 // Parameters:74 // httpContext:75 // The HTTP context, which encapsulates all HTTP-specific information about76 // an individual HTTP request.77 //78 // Returns:79 // A reference to the validation status.80 //81 // Exceptions:82 // System.ArgumentNullException:83 // The httpContext parameter is null.84 protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);85 }
这里我们要重写OnAuthorization这个方法。
接下来就看下LoginFilterAttibute这个"儿子"是怎么完成"老子"交待的任务了。直接上code
1 public class LoginFilterAttribute:AuthorizeAttribute 2 { 3 4 private static string formsCookieName = FormsAuthentication.FormsCookieName; 5 6 public override void OnAuthorization(AuthorizationContext filterContext) 7 { 8 HttpCookie formsCookie = 9 System.Web.CookieManager.GetCookie(formsCookieName);10 if (formsCookie == null)11 {12 //页面Cookie过期后返回登录页面13 RedirectToLoginPage(filterContext);14 return;15 }16 17 bool autenticated = HttpContext.Current.User.Identity.IsAuthenticated;18 19 //一旦发现身份不合法就作相应的处理.20 if (!autenticated )21 {22 //redirect to login23 RedirectToLoginPage(filterContext);24 return;25 }26 //if success add login data to context27 }28 private static void RedirectToLoginPage(AuthorizationContext filterContext)29 {30 if (filterContext.HttpContext.Request.IsAjaxRequest())31 {32 filterContext.Result = new JsonResult() 33 { 34 Data = new {35 status = "error",36 message = "Unauthorized_Message"37 },38 JsonRequestBehavior= JsonRequestBehavior.AllowGet39 };40 return;41 }42 else43 {44 //返回登录页面的相关处理..........45 } }
第二步、新建一个基类Controller-BaseController并且继承Controller。
1 [LoginFilter]//此处就是我们上面定义的LoginFilterAttribute2 public abstract partial class BaseController : Controller3 {4 public BaseController(){ 5 6 }7 //........其他相关处理8 }
第三步、不是有很多页面吗?那我只要在对应的Controller去继承那个BaseController就实现了,在访问任何一个页面都会去作相应的过滤和处理。
1 Public Class LoginController:BaseController2 {3 Public ActionResult Index()4 {5 //........6 return View();7 }8 }
以上纯属个人观点,如有雷同纯属巧合!谢谢阅读,如果对您有帮助,请点关注并推荐!