• 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还是会执行,不仅浪费资源,还会产生一些不必要的错误 

  • 相关阅读:
    成功在RedFlag Linux 5.0桌面版安装oralce10
    ORACLE ebs 11.5.10 for linux 安装心得
    C#讀取轉換Excel檔案的優化(源代碼)
    [轉]SAP BASIS经验十年James Yen
    SAP Basis 常用事务代码
    健康指南:人体十大最佳黄金时间
    中國人使筷子的十二種忌諱
    SAP basis 相关设定
    技术出身,如何做好项目经理?
    [轉貼]奋斗5年从月薪3500到700万!
  • 原文地址:https://www.cnblogs.com/li150dan/p/9957971.html
Copyright © 2020-2023  润新知