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

时间秒杀一切 提交于 2019-12-22 03:17:29

问题


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!


回答1:


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)




回答2:


from mdsn

When a user is logged in, ASP.NET sets an authentication token in a cookie that lets ASP.NET know on subsequent requests that the user has been logged in. If persistCookie is false, the token is valid only until the user closes the browser.

So, WebSecurity.CurrentUserId will only be useful on subsequent requests.

You'll have to find another way of getting to that information.




回答3:


Please restore WebSecurity connection . Add following code in the default controller as:

     public class HomeController : Controller
        {
            public ActionResult Index()
            {
                //restore WebSecurity  connection
                if (!WebSecurity.Initialized)
                WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

                ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

                return View();
            }
.......


来源:https://stackoverflow.com/questions/11262170/getting-the-currentuserid-from-websecurity-directly-after-login-c-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!