Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the CurrentUserID from Websecurity directly after login (C#/ASP.NET)

I have this website (C#/ASP.NET) with a form where the user can register for an account (it is the default template of VS11) and after everything is filled in and the user clicks to register, it creates the account and logs in the user (which works great).

After this step I want to get the UserID which he was assigned, but it doesn't work. I've put a breakpoint there to see the values of both "currentuserid" and "WebSecurity.CurrentUserId" but they only have a -1 value. Next step is the user gets redirected to the next page, and on that page these functions work. I thought I would be able to get the UserID as the user has already gotten logged in in the first line of the code I provided here.

So my question is, why doesn't it work here? I am very noobish with this, so I am obviously missing something.

WebSecurity.Login(username, password);
int currentuserid = WebSecurity.CurrentUserId; // This doesn't work, only returns -1
<here I wish to update other tables but I need the user ID>
Response.Redirect("~/Welcome.cshtml");

Thanks!

like image 394
Suedish Avatar asked Jun 29 '12 12:06

Suedish


Video Answer


1 Answers

You should use WebSecurity.GetUserId(username)

WebSecurity.Login(username, password);
int currentuserid = WebSecurity.GetUserId(username);
Response.Redirect("~/Welcome.cshtml");

Take a look here: http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity.getuserid(v=vs.99)

like image 156
Dragomir Răzvan Avatar answered Nov 02 '22 23:11

Dragomir Răzvan