mvc 添加过滤器并添加session缓存判断

功能实现:ajax

登陆时添加session缓存.判断是否登陆过时.json

1.判断是否须要登陆判断缓存

public static AdminLoginUser GetAdminLoginUser()
{
#region 获取当前登陆者信息
AdminLoginUser result = null;
try
{
if (HttpContext.Current.Session["User"] != null)
{
result = HttpContext.Current.Session["User"] as AdminLoginUser;
}
else
{
result = null;
}
}
catch (Exception ex)
{
//TTracer.WriteLog(ex.ToString());
}
return result;
#endregion
}session

 

public class SessionAndAuthority : ActionFilterAttribute//ActionFilterAttribute是Action过滤类,该属于会在执行一个action以前先执行.
    {
        //后台登陆用户
        protected AdminLoginUser adminloginUser
        {
            get
            {
                return Test1.Common.UserHelper.GetAdminLoginUser();
            }
        }

        /// <summary>
        /// 使用验证时 [NoSign] 标注不须要登陆和权限验证
        /// </summary>
        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true)]
        public class NoSignAttribute : Attribute
        {
        }

        //操做是否须要判断
        private static bool SkipNoSign(ActionExecutingContext actionContext)
        {
            return actionContext.ActionDescriptor.GetCustomAttributes(typeof(NoSignAttribute), true).Length == 1;//有NoSign属性  true
        }

        //在执行操做方法以前 判断登陆状况和页面权限
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (SkipNoSign(filterContext))//是否该类标记为NoSign,若是是则不须要判断
            {
                base.OnActionExecuting(filterContext);
                return;
            }

            #region 先判断session
            if (null == adminloginUser)
            {
                //session 过时
                if (!filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    // 请求跳转到Tip页面
                    filterContext.Result = new RedirectResult("/Home/Tip?state=0");
                }
                else
                {
                    //ajax请求 返回json格式提示
                    if (filterContext.HttpContext.Request.HttpMethod == "GET")
                    {
                        filterContext.Result = new RedirectResult("/Home/Tip?state=0");
                    }
                    else
                    {
                        ContentResult content = new ContentResult();
                        ResultMessage msg = new ResultMessage() { success = false, message = "登陆已过时,请从新登陆!" };
                        content.Content = msg.ToJson();
                        filterContext.Result = content;
                    }
                }
            }
            #endregion
        }
    }

 

 

2.登陆时添加缓存ide

HttpContext.Session["User"] = LoginUserInfo;

3.在 FilterConfig 添加过滤器 SessionAndAuthority spa

相关文章
相关标签/搜索