My.User 对象

更新:2007 年 11 月

提供对有关当前用户的信息的访问。

备注

My.User 对象公开的属性和方法提供了对有关当前用户的信息的访问。“当前用户”的含义在 Windows 和 Web 应用程序之间略有不同。在 Windows 应用程序中,当前用户是运行应用程序的用户。在 Web 应用程序中,当前用户是访问应用程序的用户。

My.User 属性还提供了对当前用户的 IPrincipal 的访问。主体对象代表用户的安全上下文,其中包括该用户的标识和用户所属的任何角色。

对于 Windows 应用程序,此属性提供的功能与 CurrentPrincipal 属性相同。对于 Web 应用程序,此属性提供的功能与 Current 属性所返回对象的 User 属性相同。

说明:

对于 Windows 应用程序,默认情况下只有基于“Windows 应用程序”模板构建的项目才会初始化 My.User 对象。在所有其他 Windows 项目类型中,您必须通过明确地调用 My.User.InitializeWithWindowsUser 方法或通过将值赋给 CurrentPrincipal 来初始化 My.User 对象。

说明:

当在 Windows 95 和 Windows 98 下运行时,My.User 对象无法报告有关当前 Windows 用户的信息,因为这些操作系统不支持已登录用户的概念。您必须实施自定义身份验证,才能在这些操作系统上使用 My.User 对象。有关更多信息,请参见演练:实现自定义身份验证和授权

任务

下表列出了涉及 My.User 对象的任务的示例。

要执行的操作

请参见

获取用户的登录名

如何:确定用户的登录名

获取用户的域名(如果应用程序使用 Windows 身份验证)

如何:确定用户的域

确定用户的角色

如何:确定用户是否属于某个组

实施自定义身份验证

演练:实现自定义身份验证和授权

示例

此示例将检查应用程序是在使用 Windows 身份验证还是自定义身份验证,并使用该信息来分析 My.User.Name 属性。

Function GetUserName() As String
    If TypeOf My.User.CurrentPrincipal Is _
    Security.Principal.WindowsPrincipal Then
        ' The application is using Windows authentication.
        ' The name format is DOMAIN\USERNAME.
        Dim parts() As String = Split(My.User.Name, "\")
        Dim username As String = parts(1)
        Return username
    Else
        ' The application is using custom authentication.
        Return My.User.Name
    End If
End Function

要求

**程序集:**Visual Basic 运行库(位于 Microsoft.VisualBasic.dll 中)

请参见

参考

My.User 对象成员

IPrincipal

CurrentPrincipal

User

Current