CBC_NS
CBC_NS

Reputation: 1957

HttpContext.Session is NULL when initializing BasePage

I have a base page which I inherit from.

public class BasePage : System.Web.UI.Page
{
    protected readonly ValueExtractor ValueExtractor;
    protected sealed override HttpContext Context => base.Context;

    public BasePage()
    {
        ValueExtractor = new ValueExtractor(new HttpContextWrapper(Context));
        ClientTimeZone = new TimeZoneHelper(OrganizationId);
    }

    public int OrganizationId
    {
        get { return ValueExtractor.ExtractValFromSession<int>("OrgId"); }
        set { Session["OrgId"] = value; }
    }
}

The problem that I'm experiencing is that OrganizationId returns 0.

The ValueExtractor.ExtractValFromSession looks like this

public T ExtractValFromSession<T>(string key, bool throwException = true)
{
    var ret = default(T);
    var typeParameterType = typeof(T);
    if (_context.Session == null) return ret; // The problem occurs here because Session is null
    var val = _context.Session[key];
    if (val != null)
    {
        try
        {
            if (typeParameterType == typeof(int))
            {
                int r;
                int.TryParse(val.ToString(), out r);
                ret = (T)Convert.ChangeType(r, typeof(T), CultureInfo.InvariantCulture);
            }
            else if (typeParameterType == typeof(bool))
            {
                bool r;
                bool.TryParse(val.ToString(), out r);
                ret = (T)Convert.ChangeType(r, typeof(T), CultureInfo.InvariantCulture);
            }
            else if(typeParameterType == typeof(string))
                ret = (T)Convert.ChangeType(val.ToString(), typeof(T), CultureInfo.InvariantCulture);
            else
                ret = (T)Convert.ChangeType(val, typeof(T), CultureInfo.InvariantCulture);

        }
        catch (Exception ex)
        {
            throw new ApplicationException($"ExtractValFromSession error: {ex.Message}");
        }
    }
    else
    {
        return ret;
    }
    return ret;
}

Upvotes: 0

Views: 102

Answers (1)

Dale
Dale

Reputation: 1941

You can't access session in constructors of pages, you will need to move this code to page_load or other methods of the page lifecycle.

More info can be the page lifecycle docs

Upvotes: 1

Related Questions