从ASP.Net Login控件的loggedIn事件获取用户名 [英] Get UserID from ASP.Net Login control LoggedIn event

查看:485
本文介绍了从ASP.Net Login控件的loggedIn事件获取用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.Net,我试图以获取用户标识(即用户GUID)的用户,只是登录,在登录控件的loggedIn事件。也就是说,我想抓住用户ID之前用户移动到下一个页面。这是code我使用的:

In ASP.Net, I am trying to get the UserId (i.e., the user GUID) of the user that just logged on, in the LoggedIn event of the Login control. That is, I want to grab the UserId before the user is moved to to the next page. This is the code I am using:

Protected Sub Login1_LoggedIn(ByVal sender As Object, _
  ByVal e As System.EventArgs) Handles Login1.LoggedIn

    Dim UserId As String
    UserId = Membership.GetUser.ProviderUserKey.ToString()

End Sub

不过,我得到一个对象引用不设置到对象的实例错误。同样的code效果很好,当我用它在随后的页面,当用户登录正在访问这些页面。

However, I get an "Object reference not set to an instance of an object" error. This same code works well when I use it in subsequent pages, when a logged in user is accessing these pages.

推荐答案

ScottGu 已经回答了这个问题,因为解释在在ASP.NET论坛这个博客帖子

ScottGu has the answer to this problem, as explained in this blog post on the ASP.NET Forum:

该事件的loggedIn立即触发
  之后,用户登录与
  登录控制 - 而不是之前的
  下一请求的站点。因此,
  用户对象不填写呢。

The LoggedIn event fires immediately after the user is logged in with the login control -- but not before the next request to the site. As such, the User object isn't filled out yet.

如果你改变code到是这样的:

If you change your code to something like:

Dim UserId As String
UserID = Membership.GetUser(Login1.UserName).ProviderUserKey.ToString()

它应该工作的罚款。调用 Membership.GetUser ,而没有经过用户名作为参数将希望抓住当前登录的用户。当然,这种失败上述原因为用户尚未填入对象。通过将登录控件的用户名属性作为参数传递给的getUser()方法,您明确强制 Membership.GetUser 方法按名称从用户存储(即数据库)指定检索用户。这确保了 Membership.GetUser 方法返回一个有效的的MembershipUser 对象允许您访问 ProviderUserKey 属性。

It should work fine. Calling Membership.GetUser without passing the Username as a parameter will expect to grab the "current" logged in user. Of course, this fails for the above reasons as the User object is not yet populated. By passing the Login control's UserName property as a parameter to the GetUser() method, you explicitly force the Membership.GetUser method to retrieve the user as specified by name from the user store (i.e. database). This ensures that the Membership.GetUser method returns a valid MembershipUser object which allows you to access the ProviderUserKey property.

这篇关于从ASP.Net Login控件的loggedIn事件获取用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆