初始化BasePage时,HttpContext.Session为NULL

时间:2017-10-13 17:22:05

标签: c# asp.net webforms

我有一个我继承的基页。

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; }
    }
}

我遇到的问题是OrganizationId返回0.

ValueExtractor.ExtractValFromSession看起来像这样

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;
}

1 个答案:

答案 0 :(得分:1)

您无法在页面构造函数中访问会话,您需要将此代码移动到page_load或页面生命周期的其他方法。

更多信息可以是the page lifecycle docs