1. Create a new custom attribute class
Public classBasefilterattribute:filterattribute, Iauthorizationfilter {/// <summary> ///Custom Extended properties, verifying user logon/// </summary> /// <param name= "Filtercontext" >The AuthorizationContext class encapsulates information about the controller, the HTTP context, the request context, the routing data, the action descriptor, and the result of the operation. </param> Public voidonauthorization (AuthorizationContext filtercontext) {if(Filtercontext.httpcontext = =NULL) { Throw NewException ("The HTTP context does not exist! "); } if(FilterContext.HttpContext.Session = =NULL) { Throw NewException ("Server session is not available! "); } if(FilterContext.ActionDescriptor.IsDefined (typeof(Allowanonymousattribute),true))return; if(Filtercontext.httpcontext.session[confighelper.sessioncookiekey]! =NULL)return; //if (filtercontext.httpcontext.request.cookies[confighelper.sessioncookiekey]==null)//Filtercontext.result = new Redirectresult ("~/views/account/login.cshtml"); if(Cookieshelper.getcookie (confighelper.sessioncookiekey) = =NULL) Filtercontext.result=NewRedirectresult (Confighelper.sessioncookiereturnurl); } }
2. Add the custom attribute to the associated controller class
[Basefilter] Public class Prelistcontroller:basecontroller { }
3. Set up methods that are not validated to allow anonymous access
[allowanonymous] public actionresult Login () { return View (); }
MVC Custom Attribute Validation Login