操作筛选器中的会话变量

本文关键字:会话 变量 筛选 操作 | 更新日期: 2023-09-27 17:58:07

我有一个操作过滤器,用于检查是否设置了会话变量ID。出于开发目的,我在检查之前手动设置了这个变量。

public class MyActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            context.HttpContext.Session.Add("ID", 123123);
            int ID = (int)context.HttpContext.Session.Contents["ID"];
            var rd = context.HttpContext.Request.RequestContext.RouteData;
            TED _db = new TED();
            //if not in DB
            if (_db.Users.Find(ID) == null && rd.GetRequiredString("action") != "NoAccess")
            {
                RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                redirectTargetDictionary.Add("action", "NoAccess");
                redirectTargetDictionary.Add("controller", "Home");
                redirectTargetDictionary.Add("area", "");
                context.Result = new RedirectToRouteResult(redirectTargetDictionary);
            }
            base.OnActionExecuted(context);
        }
    }

据我所知,这段代码是在任何页面之前运行的,这个Session["ID"]总是设置好的。如果我一直在测试,这个网站运行良好,但如果我离开它一段时间,然后尝试继续测试,它似乎会崩溃。这是我得到的错误:

int UserID = (int)Session.Contents["ID"];
System.NullReferenceException: Object reference not set to an instance of an object.

起初,我认为会话可能只是过期,但在加载任何页面之前,应该设置Session["ID"]。这里的问题是什么?

操作筛选器中的会话变量

您正在OnActionExecuted方法上实现您的actionfilter,该方法在您的操作方法之后执行

您应该实现OnActionExecuting方法

public class MyActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            context.HttpContext.Session.Add("ID", 123123);
            int ID = (int)context.HttpContext.Session.Contents["ID"];
            var rd = context.HttpContext.Request.RequestContext.RouteData;
            TED _db = new TED();
            //if not in DB
            if (_db.Users.Find(ID) == null && rd.GetRequiredString("action") != "NoAccess")
            {
                RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                redirectTargetDictionary.Add("action", "NoAccess");
                redirectTargetDictionary.Add("controller", "Home");
                redirectTargetDictionary.Add("area", "");
                context.Result = new RedirectToRouteResult(redirectTargetDictionary);
            }
            base.OnActionExecuting(context);
        }
    }