ASP.net如何使用会话?

发布于 2024-12-28 13:00:02 字数 474 浏览 0 评论 0原文

我需要将我的变量分配给会话。我尝试过这个:

string name = string.Empty
Session["N"] = name;

但行不通。

Error   1   Invalid token '[' in class, struct, or interface member declaration
Error   2   Invalid token '"N"' in class, struct, or interface member declaration   
Error   3   Identifier expected

我哪里错了?

我在 Visual Studio 2008 中使用 ASP.net。

错误 1 ​​类、结构或接口成员声明中的标记“[”无效 错误 2 类、结构或接口成员声明中的标记“N”无效
错误 3 需要标识符

I need to assign my variable to session. I tried this:

string name = string.Empty
Session["N"] = name;

and it won't work.

Error   1   Invalid token '[' in class, struct, or interface member declaration
Error   2   Invalid token '"N"' in class, struct, or interface member declaration   
Error   3   Identifier expected

Where I'm wrong?

I'm using ASP.net in Visual Studio 2008.

Error 1 Invalid token '[' in class, struct, or interface member declaration
Error 2 Invalid token '"N"' in class, struct, or interface member declaration
Error 3 Identifier expected

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

〃安静 2025-01-04 13:00:02

第一行末尾缺少 ;

string name = string.Empty;
Session["N"] = name;
string test= Session["N"].ToString();//Catch Your session

missing ; end of first line.

string name = string.Empty;
Session["N"] = name;
string test= Session["N"].ToString();//Catch Your session
无边思念无边月 2025-01-04 13:00:02

该代码没有任何问题(除了缺少分号,正如 Shree Khanal 指出的那样,但这不可能是问题,对吧?)。

只要代码位于页面类中,Session 属性就可用。如果您的代码位于不同的类中,则没有可用的 Session 属性,那么您需要从当前上下文中获取它:

HttpContext.Current.Session["N"] = name;

从会话集合中读取值时,类型为Object,而不是String,因此您需要对其进行强制转换:

string name = Session["N"] as string;

使用 as 关键字意味着您可以尝试读取该值,即使它会不存在,或者恰好被设置为不同的数据类型。在这种情况下,您将得到一个 null 引用。

There is nothing wrong with that code (except a missing semicolon, as Shree Khanal pointed out, but that can't be the issue, right?).

As long as the code is in the page class, the Session property is available. If you have the code in a different class, you don't have the Session property available, then you need to get it from the current context:

HttpContext.Current.Session["N"] = name;

When reading the value from the session collection, the type is Object, not String, so you need to cast it:

string name = Session["N"] as string;

Using the as keyword means that you can attempt to read the value even if it would not exist, or if it happens to be set to a different data type. In that case you will get a null reference back.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文