2009-06-09 81 views
0

目前,我收到錯誤「非靜態字段方法或屬性需要對象引用」。我的代碼如下:如何創建HttpContext的實例?

using MyApp.Global; 

namespace MyApp.MyNamespace 
{ 
    public class MyClass:System.Web.UI.Page 
    { 
     //Toolbox is inside Global, GetCurrentCookieData is a static method 
     private CookieData cd = Toolbox.GetCurrentCookieData(HttpContext.Current); 
     //the above was changed and resolved the first error, but another error 
     //just popped up. Below, I get the error: cd denotes field 
     //where class was expected 
     private int CompanyID = Util.GetCompanyIDByUser(cd.Users); 

     protected override void OnLoad(EventArgs e) 
     { 
      //snip 
     }   

     protected void MyEventHandler(object sender, EventArgs e) 
     { 
      //snip 
     } 
    } 
} 

目前,我的每一個方法需要使用CD,所以不是創建每個方法中的變量,我一直在尋找一種方式來聲明它的類,可將其到所有方法。當我嘗試在方法中設置cd時,它工作正常。我搜索了一下,似乎我必須有一個頁面的實例才能在那裏使用,但這不起作用。所以我真的誤解了這是如何工作的。任何人都可以將我指向正確的方向嗎?

編輯:我添加了靜態關鍵字到CD,爲了解決'cd表示期望類'的錯誤。這是很好的實現嗎?

編輯:我打算在下面標記正確答案並提出一個新問題,因爲我認爲這是值得的。

回答

6

嘗試使用System.Web.HttpContext.Current

+0

它看起來像做了工作,但我必須澄清我的問題,因爲它看起來稍微有點多。 – 2009-06-09 18:42:15

1

如已經建議的那樣使用HttpContext.Current。

對於您的其餘問題:嘗試是否可以在OnInit中創建cd字段,然後在OnLoad和其他方法中使用它。你的問題可以提出,當構造頁面對象時,HttpContext還不可用。 (見the ASP .NET Page Life Cycle

1

普羅蒂普:總結該cookie在受保護的屬性:

protected CookieData CurrentCookie 
{ 
    get { return HttpContext.Current.CookieData; } 
} 

然後所有的方法都引用在頁面上。我懷疑你可能想要做的是將一個特定的cookie值包裝在一個屬性中並傳遞給它。