功能实现:
登录时添加session缓存.判断是否登录过期.
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
}
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.登录时添加缓存
HttpContext.Session["User"] = LoginUserInfo;
3.在 FilterConfig 添加过滤器 SessionAndAuthority