Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current.Session is null

Tags:

c#

asp.net

I have a WebSite with a custom Cache object inside a class library. All of the projects are running .NET 3.5. I would like to convert this class to use Session state instead of cache, in order to preserve state in a stateserver when my application recycles. However this code throws an exception with "HttpContext.Current.Session is null" when I visit the methods from my Global.asax file. I call the class like this:

Customer customer = CustomerCache.Instance.GetCustomer(authTicket.UserData);

Why is the object allways null?

public class CustomerCache: System.Web.SessionState.IRequiresSessionState
{
    private static CustomerCache m_instance;

    private static Cache m_cache = HttpContext.Current.Cache;

    private CustomerCache()
    {
    }

    public static CustomerCache Instance
    {
        get
        {
            if ( m_instance == null )
                m_instance = new CustomerCache();

            return m_instance;
        }
    }

    public void AddCustomer( string key, Customer customer )
    {
        HttpContext.Current.Session[key] = customer;

        m_cache.Insert( key, customer, null, Cache.NoAbsoluteExpiration, new TimeSpan( 0, 20, 0 ), CacheItemPriority.NotRemovable, null );
    }

    public Customer GetCustomer( string key )
    {
        object test = HttpContext.Current.Session[ key ];

        return m_cache[ key ] as Customer;
    }
}

As you can see I've tried to add IRequiresSessionState to the class but that doesn't make a difference.

Cheers Jens

like image 495
M Raymaker Avatar asked May 03 '11 11:05

M Raymaker


1 Answers

It isn't really about including the State inside your class, but rather where you call it in your Global.asax. Session isn't available in all the methods.

A working example would be:

using System.Web.SessionState;

// ...

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
        {
            HttpContext context = HttpContext.Current;
            // Your Methods
        }
    }

It will not work e.g. in Application_Start

like image 112
Dennis Röttger Avatar answered Sep 18 '22 09:09

Dennis Röttger