2014-01-16 17 views
0

我想檢查ASP.NET網站(WebForms)中會話的值。 所以我試圖做的是:我無法獲取會話的值並在if()語句中使用它

// This file called 'Encryptor.cs' and is located under the 'App_Code' folder. 

using System; 
using System.Data; 
using System.Data.OleDb; 
using System.Security.Cryptography; 
using System.Text; 

public static class Encryptor 
{ 
    public static bool CheckLoginStatus() 
    { 
     bool LoginStatus = false; 

     if ((string)Session["username"] == null) 
     { 
      LoginStatus = true; 
     } 

     return LoginStatus; 
    } 
} 

我不斷收到這樣的信息:「‘會議’的名稱不在當前環境下存在的。」 我該如何解決它?

+1

看看這個帖子:如何從任何類訪問會話變量ASP.NET?](http://stackoverflow.com/questions/621549/how-to-access-session-variables-from-any-class-in-asp-net)接受的答案很不錯。 – scheien

+0

謝謝!它工作 –

回答

1

您應該能夠訪問會話變量是這樣的:

string username = (string)System.Web.HttpContext.Current.Session["username"]; 

的HttpContext駐留在System.Web命名空間。您可以通過using System.Web引用命名空間,或者在訪問會話時轉到完整的命名空間。

如果你想擴展會議的有效性,以及對變量的強類型,那麼你可以選擇在這樣的解決方案:How to access session variables from any class in ASP.NET?

+0

但現在它說:「名稱'HttpContext'不存在於當前的上下文中。」 ||編輯:我應該添加System.Web之前,你已經建議。現在它可以工作。 –

+2

您需要引用整個名稱空間。或者在頂部添加'使用System.Web',或者'System.Web.HttpContext.Current.Session [「username」]' – scheien