User login validation filter in asp.net mvc

 Create a class in the WEB project:

     public class LoginFilter : ActionFilterAttribute

 

    {

 

        public override void OnActionExecuting(ActionExecutingContext filterContext)

 

        {

 

            //HttpContext.Current.Response.Write("OnActionExecuting: Execute when the Action is about to be executed but not executed <br />");

 

            if (HttpContext.Current.Session"admin" == null)

 

            {

 

                //HttpContext.Current.Response.Write("js code");
                //HttpContext.Current.Response.End();
                //return;

                var context = new ContentResult();
                context.Content = "<script>alert( 'Please log in again!');location.href='/Login/Index'</script>";

                filterContext.Result = context;

 

 

 

            }

 

        }

 

 

 

        public override void OnActionExecuted(ActionExecutedContext filterContext)

 

        {

 

            //HttpContext.Current.Response.Write("OnActionExecuted: Executed when the Action executes but has not returned the result<br />");

 

        }

 

 

 

        public override void OnResultExecuting(ResultExecutingContext filterContext)

 

        {

 

            // HttpContext.Current.Response.Write("OnResultExecuting:OnResultExecuting is also the same as OnActionExecuted, but the former is executed after the latter is executed<br />");

 

        }

 

 

 

        public override void OnResultExecuted(ResultExecutedContext filterContext)

 

        {

 

            // HttpContext.Current.Response.Write("OnResultExecuted: is executed when the ActionResult will be returned after the Action is executed<br />");

 

        }

 

    }

 

 

 

 

 

To use the method, write directly outside the method in the control, such as:

 

     [LoginFilter]
        public ActionResult Add()
        {
            Model.Userinfo loginuser = base.GetLoginUser();
            Model.Product pro = new Model.Product() { userid = loginuser.id, username = loginuser.username };
            return View(pro);
        }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326123715&siteId=291194637