登录后直接从网络安全获取当前用户 ID (C#/ASP.NET)



我有一个网站(C#/ASP.NET),其中包含一个表单,用户可以在其中注册一个帐户(它是VS11的默认模板),并且在填写所有内容并且用户单击注册后,它会创建帐户并登录用户(效果很好)。

完成此步骤后,我想获取分配给他的UserID,但它不起作用。我在那里放置了一个断点以查看"currentuserid"和"WebSecurity.CurrentUserId"的值,但它们只有一个-1值。下一步是将用户重定向到下一页,在该页面上,这些功能起作用。我以为我将能够获得UserID,因为用户已经在我在此处提供的代码的第一行中登录。

所以我的问题是,为什么它在这里不起作用?我对此非常菜鸟,所以我显然错过了一些东西。

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");

谢谢!

你应该使用 WebSecurity.GetUserId(用户名)

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

看看这里: http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity.getuserid(v=vs.99)

来自 mdsn

当用户登录时,ASP.NET Cookie 中设置身份验证令牌,ASP.NET 在后续请求中知道用户已登录。如果 persistCookie 为 false,则令牌仅在用户关闭浏览器之前有效。

因此,WebSecurity.CurrentUserId 仅在后续请求中有用。

您必须找到另一种获取该信息的方法。

请恢复网络安全连接。在默认控制器中添加以下代码:

     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();
            }
.......

最新更新