C# Asp.net 会话变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9623150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:14:30  来源:igfitidea点击:

Asp.net session variable

c#asp.netsession-variables

提问by Amaranth

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.

我有一个带有 c# 代码的 asp.net 项目。我有一个名为 GlobalVariable 的静态类,我在其中存储一些信息,例如当前选择的产品。

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.

我想创建(从 c# 代码)某种仅从 c# 代码使用的会话变量,但不仅从页面,而且从任何类。

采纳答案by driis

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.

要从非页面类访问 Session 对象,您应该使用HttpContext.Current.Session.

回答by Yuck

GlobalVariableis a misleading name. Whatever it's called, it shouldn't be staticif it's per session. You can do something like this instead:

GlobalVariable是一个误导性的名字。不管它叫什么,static如果它是每个会话,它不应该是。你可以这样做:

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

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

您也不应该尝试使 Session集合全局可访问。相反,只传递您需要的数据并Session在适当的地方使用获取/设置。

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

这是在 MSDN 上的ASP .NET 中使用会话存储的概述。

回答by Khan

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.

你有点回答了你自己的问题。答案在会话变量中。在您的 GlobalVariable 类中,您可以放置​​由会话变量支持的属性。

Example:

例子:

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