1. Example One
/// <summary> ///require user login action to perform advance validation/// </summary> Public classLoginfilterattribute:filterattribute, Iactionfilter {voidiactionfilter.onactionexecuted (ActionExecutedContext filtercontext) {}/// <summary> ///Verify that the user is logged in before executing the action, if no login returns a string physique/// </summary> /// <param name= "Filtercontext" ></param> voidiactionfilter.onactionexecuting (ActionExecutingContext filtercontext) {//throw new NotImplementedException (); //1. Judging if(A_userhelper.islogin () = =false) {Contentresult result=NewContentresult (); Result. Content="Pro, have not logged in, please login first"; Filtercontext.result=result; } } }
2. Example Two
Public classLogingoattribute:filterattribute, Iactionfilter {voidiactionfilter.onactionexecuted (ActionExecutedContext filtercontext) {//throw new NotImplementedException (); } /// <summary> ///Verify that the user is logged in before executing the action, and return to the landing page if not logged in/// </summary> /// <param name= "Filtercontext" ></param> voidiactionfilter.onactionexecuting (ActionExecutingContext filtercontext) {//throw new NotImplementedException (); if(A_userhelper.islogin () = =false) { //do not jump to the current address to return to the landing page------//routedata route = filtercontext.routedata; //route. values["Controller"] = "user"; //route. Values["action"] = "Login"; //IController IController = new Usercontroller (); //httpcontextbase context = Filtercontext.httpcontext; //Icontroller.execute (New RequestContext (context, route)); //Filtercontext.result = new Contentresult (); //redirect to landing page--------deprecated because the current action still executes//httpcontextbase context = Filtercontext.httpcontext; //context. Response.Redirect (Siteurl.getlogin (), true); //context. Response.End (); //filtercontext.actiondescriptor = null; //temporarily redirect to landing pageHttprequestbase req =filterContext.HttpContext.Request; stringurl = siteurl.getlogin () +"? redirecturl="+req. Url.absoluteuri; Redirectresult result=NewRedirectresult (URL,false); Filtercontext.result=result; //This method failed//httpcontextbase context = Filtercontext.httpcontext; //Usercontroller UserC = new Usercontroller (); //userc.controllercontext = new ControllerContext (); //userc.controllercontext.routedata.datatokens["Controller"] = "user"; //userc.controllercontext.routedata.values["area"] = ""; //Contentresult content = new Contentresult (); //content. Content = viewhelper.renderviewtostring (UserC, "login", null);; //filtercontext.result = content; } } }
Filter usage Examples