[英]Asp.NET C# Session Variables from class to handler
為了避免使用查詢字符串,我正在嘗試使用 session 變量來傳遞所需的值。 我正在從 class 到處理程序執行此操作。
在 class 我使用:
HttpContext.Session["name"] = "Value";
在我使用的處理程序中:
var name = context.Session["name"];
我已經添加了IReadOnlySessionState
或IRequiresSessionState
,但 session 變量仍然是 null。
一些幫助?
我認為你又在創造新的背景。 您應該使用HttpContext.Current
使用相同的會話。 嘗試像下面這樣的代碼並參考我在下面添加的評論。
string firstName = "Jeff";
string lastName = "Smith";
string city = "Seattle";
// Save to session state in a Web Forms page class.
Session["FirstName"] = firstName;
Session["LastName"] = lastName;
Session["City"] = city;
// Read from session state in a Web Forms page class.
firstName = (string)(Session["FirstName"]);
lastName = (string)(Session["LastName"]);
city = (string)(Session["City"]);
// Outside of Web Forms page class, use HttpContext.Current.
HttpContext context = HttpContext.Current;
context.Session["FirstName"] = firstName;
firstName = (string)(context.Session["FirstName"]);
我意識到這是一篇舊帖子,但其他人可能會覺得這很有用。
嘗試將 HttpContext.Current 作為參數傳遞給您常用的 class 中的例程。
來自 web forms class 的代碼:
protected void SetSessionValue()
{
var CurrentSession = HttpContext.Current;
oCommonClass.cSetSessionValue(CurrentSession);
var SessionValue = Session("SessionValue");
}
來自公共 class 的代碼:
public void cSetSessionValue(object cCurrentSession)
{
var cSessionValue = "New Value";
cCurrentSession.Session("SessionValue") = cSessionValue;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.