2017-10-13 76 views
0

我有一個我從中繼承的基頁。初始化BasePage時HttpContext.Session爲NULL

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

你不需要聲明上下文。您正在從頁面繼承,因此您已經有權訪問它。 – VDWWD

回答

1

您不能在頁面構造函數訪問會話,您需要將此代碼移至page_load或頁面生命週期的其他方法。

更多的信息可以是the page lifecycle docs

相關問題