与 @Session[“something_here”] 混淆的结果 (C#/Razor)

发布于 2024-11-14 02:59:37 字数 662 浏览 6 评论 0原文

我正在一个基本网页中测试一些东西,我注意到一些非常奇怪的事情。我不确定这种行为是否是预期的,但它确实让我想知道...

我知道我可以获取当前登录者的当前用户 ID,如下所示:

@WebSecurity.CurrentUserId

并且只是为了查看会话是如何使用的,我想,一旦用户登录,我就将 CurrentUserId 存储在 Session 变量中(作为示例),如下所示:

@Session["UserIDthing"] = @WebSecurity.CurrentUserId;

然后在另一个页面上,我只输出会话 id(它应该完全等于 1,因为那是我的 UserId 是什么),如下所示:

@Session["UserIDthing"]

但是,它不是输出“1”,而是输出负 1“-1”。为什么会出现这种情况?

在此处输入图像描述

为了确保我对用户 ID 的理解是正确的,我使用

@WebSecurity.CurrentUserId

以下 方法输出了用户 ID:显示正确的ID,只是“1”

I am testing a few things here in a basic webpage, and I noticed something very odd. I'm not sure if this behavior is to be expected, but it does make me wonder...

I know I can get the Current User ID of the person currently logged in, like so:

@WebSecurity.CurrentUserId

And just to see how Sessions are used, I thought I'd just store (as an example) the CurrentUserId in a Session variable once the user logs in, like this:

@Session["UserIDthing"] = @WebSecurity.CurrentUserId;

And then on another page, I just output the session id (which should be exactly equal to 1, because thats what my UserId is), like this:

@Session["UserIDthing"]

But, instead of it outputting "1", it outputs minus 1 "-1". Why does this happen?

enter image description here

And just to make sure I was right about the user id, I outputted the user id using:

@WebSecurity.CurrentUserId

And it displayed the correct ID, which is just "1"

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

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

发布评论

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

评论(2

时光瘦了 2024-11-21 02:59:37

它可能与Session无关。尝试以其他方式存储 @WebSecurity.CurrentUserId 以确保 CurrentUserId 在用户登录后实际上已设置(可能通过将其记录到文件或使用用于测试的静态变量)。

It probably has nothing to do with Session. Try to store the @WebSecurity.CurrentUserId some other way to ensure that the CurrentUserId has actually been set after the user logs in (maybe by logging it to a file or use a static variable for testing).

疑心病 2024-11-21 02:59:37

要分配变量,您需要一个代码块,而不是输出块。您应该使用:

@{ someVar = otherVar; }

您使用的语法:

@someVar = @otherVar;

翻译为(伪代码):

Response.Write(HtmlEncode(someVar));
Response.Write(" = ");
Response.Write(HtmlEncode(otherVar));
Response.Write(";");

BTW:为什么要在视图中分配会话变量。这应该是控制者的责任。

To assign a variable, you need a code block, not an output block. You should use:

@{ someVar = otherVar; }

The syntax you use:

@someVar = @otherVar;

is translated as (pseudo code):

Response.Write(HtmlEncode(someVar));
Response.Write(" = ");
Response.Write(HtmlEncode(otherVar));
Response.Write(";");

BTW: Why do you assign session variables in your view. This should be the responsability of the controller.

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