登录后直接从Websecurity获取CurrentUserID(C#/ ASP.NET)

我有这个网站(C#/ ASP.NET),其中一个表单,用户可以注册一个帐户(它是VS11的默认模板),在填写完所有内容并且用户点击注册后,它会创建帐户和日志在用户(这很棒)。

在这一步之后,我想获得他被分配的UserID,但它不起作用。 我在那里放了一个断点来查看“currentuserid”和“WebSecurity.CurrentUserId”的值,但它们只有-1值。 下一步是用户被重定向到下一页,在该页面上这些function起作用。 我以为我能够获得UserID,因为用户已经在我在这里提供的代码的第一行登录了。

所以我的问题是,为什么它不起作用? 我对此很无礼,所以我显然缺少一些东西。

WebSecurity.Login(username, password); int currentuserid = WebSecurity.CurrentUserId; // This doesn't work, only returns -1  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中设置一个身份validation令牌,让ASP.NET知道用户已登录的后续请求。如果persistCookie为false,则令牌仅在用户关闭浏览器之前有效。

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

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

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