从类到处理程序的Asp.NET C#会话变量
问题描述:
我试图避免使用querystrings来使用会话变量来传递所需的值。 我正在从一个类到一个处理程序。从类到处理程序的Asp.NET C#会话变量
在课堂上使用:
HttpContext.Session["name"] = "Value";
在我使用的处理程序:
var name = context.Session["name"];
我已经添加了IReadOnlySessionState
或IRequiresSessionState
但会话变量保持空。
有帮助吗?
答
我想你正在重新创建新的上下文。您应该使用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"]);
嗨。感谢您的回答...但它不工作... 我设置类中的值,但在处理程序,它仍然为空。 – user3330412