12

我有这个网站(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");

谢谢!

4

3 回答 3

20

您应该使用 WebSecurity.GetUserId(username)

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)

于 2012-06-29T13:35:32.653 回答
3

来自 mdsn

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

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

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

于 2012-06-29T13:25:48.063 回答
0

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

     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();
            }
.......
于 2015-04-08T14:12:32.380 回答