与 @Session[“something_here”] 混淆的结果 (C#/Razor)
我正在一个基本网页中测试一些东西,我注意到一些非常奇怪的事情。我不确定这种行为是否是预期的,但它确实让我想知道...
我知道我可以获取当前登录者的当前用户 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?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它可能与
Session
无关。尝试以其他方式存储@WebSecurity.CurrentUserId
以确保CurrentUserId
在用户登录后实际上已设置(可能通过将其记录到文件或使用用于测试的静态变量)。It probably has nothing to do with
Session
. Try to store the@WebSecurity.CurrentUserId
some other way to ensure that theCurrentUserId
has actually been set after the user logs in (maybe by logging it to a file or use a static variable for testing).要分配变量,您需要一个代码块,而不是输出块。您应该使用:
您使用的语法:
翻译为(伪代码):
BTW:为什么要在视图中分配会话变量。这应该是控制者的责任。To assign a variable, you need a code block, not an output block. You should use:
The syntax you use:
is translated as (pseudo code):
BTW: Why do you assign session variables in your view. This should be the responsability of the controller.