动作过滤器中的会话变量

时间:2013-02-06 17:29:09

标签: c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我有一个动作过滤器检查是否设置了会话变量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"]应该被设置。这是什么问题?

1 个答案:

答案 0 :(得分:26)

您正在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);
        }
    }