2012-07-12 57 views
35

我想在.ashx文件中訪問一些值(已經在.aspx文件中設置)。我嘗試使用查詢字符串,會話等獲取該值,但每次失敗。任何人都可以建議我如何訪問.ashx文件中的會話值?如何訪問.ashx文件中的會話?

+0

「HttpContext.Current.Session」我已經嘗試這種對接總是例外。 – 2012-07-12 07:50:06

+4

你有什麼異常? – mrd 2012-07-12 09:38:28

+0

@mrd +1 - 一切都可能以幾千種方式失敗.. :) – Onkelborg 2012-07-12 09:42:25

回答

40

在aspx文件:

Session.Add("filename", "Test.txt"); 


在您設置在aspx文件會話值。使用以下命令獲取ashx文件中的值。

在ashx的文件:

public class ImageHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
     string Name = ""; 
     if (context.Session["filename"] != null) 
     Name = context.Session["filename"].ToString(); 
    } 
} 
+0

如何設置會話變量? context.Session [「filename」] =「somevalue」; 是不是? – efirat 2012-09-15 11:42:52

+1

如果您在aspx頁面中設置會話變量,那麼只需使用Session(「filename」)=「somevalue」。如果你在上面設置處理程序,那麼使用context.Session [「filename」] =「somevalue」。 – mrd 2012-09-17 11:50:34

+9

這個答案的關鍵部分是必須修改處理程序以從IRequiresSessionState繼承以訪問會話。 – 2013-12-24 12:58:24

0

試試這個,

HttpContext.Current.Session 
+4

這仍然需要上面的答案信息 – 2016-02-22 15:24:05

51

在ashx.cs文件,也是 「實現」 的接口System.Web.SessionState.IReadOnlySessionStateSystem.Web.SessionState.IRequiresSessionState

您不需要實現任何方法,只需通過context.Session即可使會話可用(以只讀模式或讀/寫模式)。

頭看起來像:

public class MyHandler: IHttpHandler, System.Web.SessionState.IReadOnlySessionState 
+0

謝謝!!!!! – kevin 2012-12-14 02:38:43

+0

太棒了!在某種程度上挽救了我的生命。謝謝! – 2012-12-24 07:17:27

+2

我愛你。出於某種原因,此問題僅在Visual Studio 2013(VS2013)中體現。可能是因爲它使用的.NET版本或IIS Express版本(IIS 7?)感謝您的幫助! – Suamere 2014-03-16 21:35:48