开发者

Confusing Result with @Session["something_here"] (C#/Razor)

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开发者_JAVA百科...

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?

Confusing Result with @Session["something_here"] (C#/Razor)

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"


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜