ASP. net mvc uses AuthorizeAttribute to handle access identity validity and Cookie expiration issues,
It has been almost half a year since I came to Shanghai. Time passes through without any further attention. Time passes away, but it is not so busy. In my spare time, there are still many blog parks, I remember when I visited the blog last time, I saw a comrade asking about how to handle the Cookie expiration in MVC. He explained that it was impossible to manually process all the pages one by one. In fact, the most amazing thing about MVC is to make perfect use of the Attribute. Let's take a look at how it works!
Step 1,We need to define a login filter tag-LoginFilterAttribute and inherit the AuthorizeAttribute. Let's see what it looks like internally.
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 }
Here we will rewrite the OnAuthorization method.
Next, let's take a look at how loginfilteratti.pdf's "son" completed the task described by Lao Tzu. Directly Add 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 // After the page Cookie expires, return to the logon page 13 RedirectToLoginPage (filterContext); 14 retur N; 15} 16 17 bool autenticated = HttpContext. Current. User. Identity. IsAuthenticated; 18 19 // process the request if the Identity is found invalid. 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 // return the related processing on the logon page .......... 45}
}
Step 2,Create a base class Controller-BaseController and inherit the Controller.
1 [LoginFilter] // The LoginFilterAttribute2 public abstract partial class BaseController defined above: Controller3 {4 public BaseController () {5 6} 7 //........ other related processing 8}
Step 3,Isn't there many pages? Then, I only need to inherit the BaseController from the corresponding Controller. when accessing any page, I will perform Corresponding filtering and processing.
1 Public Class LoginController:BaseController2 {3 Public ActionResult Index()4 {5 //........6 return View();7 }8 }
The above are purely personal opinions. If there are similarities, it is a coincidence! Thank you for reading this article. If it is helpful to you, please pay attention to it and recommend it!