Asp.net session variable

时间秒杀一切 提交于 2019-12-20 18:28:17

问题


I have a asp.net project with c# code behind. I have a static class called GlobalVariable where I store some information, like the currently selected product for example.

However, I saw that when there are two users using the website, if one changes the selected product, if changes it for everybody. The static variables seem to be commun to everybody.

I would want to create (from the c# code) some kind of session variable used only from the c# code, but not only from the page, but from any class.


回答1:


Yes static variables are shared by the whole application, they are in no way private to the user/session.

To access the Session object from a non-page class, you should use HttpContext.Current.Session.




回答2:


GlobalVariable is a misleading name. Whatever it's called, it shouldn't be static if it's per session. You can do something like this instead:

// store the selected product
this.Session["CurrentProductId"] = productId;

You shouldn't try to make the Session collection globally accessible either. Rather, pass only the data you need and get / set using Session where appropriate.

Here's an overview on working with session storage in ASP .NET on MSDN.




回答3:


You sort of answered your own question. An answer is in session variables. In your GlobalVariable class, you can place properties which are backed by session variables.

Example:

public string SelectedProductName 
{
    get { return (string)Session["SelectedProductName"]; }
    set { Session["SelectedProductName"] = value; }
}


来源:https://stackoverflow.com/questions/9623150/asp-net-session-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!