MVC中的action验证登录(ActionFilterAttribute)

方法一 : 1. 创建一个全局action过滤器  (在appstart  的 filterconfig中注册   filters.Add(new LoginFilterAttribute());)

                 这样就每个Action都会执行此过滤器,而不必每个Controller顶部都加上标签。                

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            //注册全局过滤器
            filters.Add(new LoginFilterAttribute() { Message = "全局" });
        }
    }

           2不需要登录的contoller或者action  则在该类或者action上添加该过滤器特性 (isNeed=false)                 

{
       [LoginFilterAttribute(isNeed = false)]
       public class UserController : Controller
       {
               public ActionResult Login()
               {
                    return View();
               }
       }
}

 方法二: 1. 创建一个filter 不在全局注册

             2. 创建 一个baseControler ,然后再basecontroller上边添加该filter特性

             3. 需要登录的则继承该basecontroller,不需要登录的则不继承该basecontroller

              补充:若是不想建baseControler ,可以直接在Controller控制器上或者Action方法上加自定义的过滤器

   注意: 1. OnActionExecuting 中   base.OnActionExecuting(filterContext);

                 如果当前项目有多个filter则加上 base.OnActionExecuting(filterContext); 

                 不添加则不会执行其他的filter 

             2. filterContext.Result = new RedirectResult("/User/login");

              在filter里边页面跳转用  filterContext.Result = new RedirectResult("/User/login");

              如果用 filterContext.HttpContext.Response.Redirect("/User/login");  则在跳转后还会继续执行  后边的action  eg: home/index    跳转user/login  后,还会接着执行index/action  里边的方法

              在Filter中用Response.Redirect,虽然URL是跳转了,但是之后的Filter和Action还是会执行,不仅浪费资源,还会产生一些不必要的错误 

原文地址:https://www.cnblogs.com/li150dan/p/9957971.html