自定义类中的HttpContext会话始终为null

时间:2012-11-12 10:29:27

标签: asp.net-mvc asp.net-mvc-3 httpcontext

我正在尝试访问自定义类中的会话变量,如下所示:

控制器:

    public void RemoveMachinesListChanged(object sender, RemovePackageEvent e)
    {
        PackageActionStatus.Current.Machines = e.Machines;
        // Dictionary<int, int> machines =  e.Machines;
    }

public class PackageActionStatus
{
    public static PackageActionStatus Current
    {
        get
        {
            HttpContextWrapper context = new HttpContextWrapper(System.Web.HttpContext.Current);
            var session = (PackageActionStatus)context.Session["PackageActionStatus"];
            if (session == null)
            {
                session = new PackageActionStatus();
                context.Session["PackageActionStatus"] = session;
            }

            return session;
        }
    }

    private Dictionary<int, int> machines;

    public Dictionary<int, int> Machines
    {
        get
        {
            return this.machines;
        }
        set
        {
            if (this.machines == null)
            {
                this.machines = new Dictionary<int, int>();
            }

            this.machines = value;
        }
    }
}

我在这里想要实现的是通过AJAX调用从/向会话变量存储和检索值。似乎每当我使用ajax时,HttpContext都为null。我该怎么办? 感谢

1 个答案:

答案 0 :(得分:0)

HttpContext在请求生命周期的某些点可用。此外,它仅在请求的主题中可用。

实施IHttpHandler,其中ProcessRequest方法将请求的HttpContext实例作为输入参数(了解有关MSDN http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.aspx的更多信息)。

在此处查看ProcessRequest示例实施:http://msdn.microsoft.com/en-us/library/system.web.ihttphandler.processrequest.aspx