SqlMembershipProvider.GetUser 方法

定义

从数据源获取成员资格用户的信息。Gets the information for a membership user from the data source.

重载

GetUser(String, Boolean)

从 SQL Server 成员资格数据库返回用户的信息,并提供更新用户的上次活动日期/时间戳的可选功能。Returns information from the SQL Server membership database for a user and provides an option to update the last activity date/time stamp for the user.

GetUser(Object, Boolean)

从数据源获得与指定的唯一标识符关联的成员资格用户的信息,并更新该用户的上次活动日期/时间戳(如果指定)。Gets the information from the data source for the membership user associated with the specified unique identifier and updates the last activity date/time stamp for the user, if specified.

GetUser(String, Boolean)

从 SQL Server 成员资格数据库返回用户的信息,并提供更新用户的上次活动日期/时间戳的可选功能。Returns information from the SQL Server membership database for a user and provides an option to update the last activity date/time stamp for the user.

public:
 override System::Web::Security::MembershipUser ^ GetUser(System::String ^ username, bool userIsOnline);
public override System.Web.Security.MembershipUser GetUser (string username, bool userIsOnline);
override this.GetUser : string * bool -> System.Web.Security.MembershipUser
Public Overrides Function GetUser (username As String, userIsOnline As Boolean) As MembershipUser

参数

username
String

要获取其信息的用户名。The name of the user to get information for.

userIsOnline
Boolean

设置为 true 则更新用户的上次活动日期/时间戳;设置为 false 则返回用户信息而不更新用户的上次活动日期/时间戳。true to update the last activity date/time stamp for the user; false to return user information without updating the last activity date/time stamp for the user.

返回

一个 MembershipUser 对象,它表示指定的用户。A MembershipUser object representing the specified user. 如果在数据库中没有找到指定的 username 值所对应的用户,则返回 nullIf no user is found in the database for the specified username value, null is returned.

异常

username 的长度超过 256 个字符。username exceeds 256 characters.

-or- username 包含一个逗号。username contains a comma.

usernamenullusername is null.

示例

下面的代码示例使用GetUser方法来确定在检索用户的密码之前是否存在用户。The following code example uses the GetUser method to determine whether a user exists before retrieving the password for the user.

备注

此示例使用MembershipdefaultProvider在 web.config 文件中SqlMembershipProvider调用指定的。This example uses the Membership class to call the SqlMembershipProvider specified as the defaultProvider in the Web.config file. 如果需要以类型SqlMembershipProvider访问默认提供程序,则可以Provider强制转换Membership类的属性。If you need to access the default provider as the type SqlMembershipProvider, you can cast the Provider property of the Membership class. 若要以特定的提供程序类型访问其他已配置的提供程序,可以使用Providers Membership类的属性访问这些提供程序,并将其转换为特定的提供程序类型。To access other configured providers as a specific provider type, you can access them by their configured name with the Providers property of the Membership class and cast them as the specific provider type.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Net.Mail" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

public void Page_Load(object sender, EventArgs args)
{
  if (!Membership.EnablePasswordRetrieval)
  {
    FormsAuthentication.RedirectToLoginPage();
  }

  Msg.Text = "";

  if (!IsPostBack)
  {
    Msg.Text = "Please enter a user name.";
  }
  else
  {
    VerifyUsername();
  }
}


public void VerifyUsername()
{
    MembershipUser user = Membership.GetUser(UsernameTextBox.Text, false);

    if (user == null)
    {
      Msg.Text = "The user name " + Server.HtmlEncode(UsernameTextBox.Text) + " was not found. Please check the value and re-enter.";

      QuestionLabel.Text = "";
      QuestionLabel.Enabled = false;
      AnswerTextBox.Enabled = false;
      EmailPasswordButton.Enabled = false;
    }
    else
    {
      QuestionLabel.Text = user.PasswordQuestion;
      QuestionLabel.Enabled = true;
      AnswerTextBox.Enabled = true;
      EmailPasswordButton.Enabled = true;
    }
}


public void EmailPassword_OnClick(object sender, EventArgs args)
{
  // Note: Returning a password in clear text using email is not recommended for
  // sites that require a high level of security.

  try
  {
    string password = Membership.Provider.GetPassword(UsernameTextBox.Text, AnswerTextBox.Text);
    MembershipUser u = Membership.GetUser(UsernameTextBox.Text);
    EmailPassword(u.Email, password);
    Msg.Text = "Your password was sent via email.";
  }
  catch (MembershipPasswordException e)
  {
    Msg.Text = "The password answer is incorrect. Please check the value and try again.";
  }
  catch (System.Configuration.Provider.ProviderException e)
  {
    Msg.Text = "An error occurred retrieving your password. Please check your values " +
               "and try again.";
  }
}


private void EmailPassword(string email, string password)
{
  try
  {
    MailMessage Message = new MailMessage("administrator", email);
    Message.Subject = "Your Password";
    Message.Body = "Your password is: " + Server.HtmlEncode(password);

    SmtpClient SmtpMail = new SmtpClient("SMTPSERVER");
    SmtpMail.Send(Message);
  }
  catch 
  {
    Msg.Text = "An exception occurred while sending your password. Please try again.";
  }
}

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Sample: Retrieve Password</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Retrieve Password</h3>

  <asp:Label id="Msg" runat="server" ForeColor="maroon" /><br />

  Username: <asp:Textbox id="UsernameTextBox" Columns="30" runat="server" AutoPostBack="true" />
            <asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                        ControlToValidate="UsernameTextBox" ForeColor="red"
                                        Display="Static" ErrorMessage="Required" /><br />

  Password Question: <b><asp:Label id="QuestionLabel" runat="server" /></b><br />

  Answer: <asp:TextBox id="AnswerTextBox" Columns="60" runat="server" Enabled="false" />
          <asp:RequiredFieldValidator id="AnswerRequiredValidator" runat="server"
                                      ControlToValidate="AnswerTextBox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" Enabled="false" /><br />

  <asp:Button id="EmailPasswordButton" Text="Email My Password" 
              OnClick="EmailPassword_OnClick" runat="server" Enabled="false" />

</form>

</body>
</html>

<%@ Page Language="VB" %>

<%@ Import Namespace="System.Web.Security" %>
<%@ Import Namespace="System.Net.Mail" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  Public Sub Page_Load(ByVal sender As Object, ByVal args As EventArgs)

    If Not Membership.EnablePasswordRetrieval Then
      FormsAuthentication.RedirectToLoginPage()
    End If

    Msg.Text = ""

    If Not IsPostBack Then
      Msg.Text = "Please enter a user name."
    Else
      VerifyUsername()
    End If

  End Sub


  Private Sub VerifyUsername()

    Dim user As MembershipUser = Membership.GetUser(UsernameTextBox.Text, False)

    If user Is Nothing Then
      Msg.Text = "The user name " & Server.HtmlEncode(UsernameTextBox.Text) & " was not found. Please check the value and re-enter."

      QuestionLabel.Text = ""
      QuestionLabel.Enabled = False
      AnswerTextBox.Enabled = False
      EmailPasswordButton.Enabled = False
    Else
      QuestionLabel.Text = user.PasswordQuestion
      QuestionLabel.Enabled = True
      AnswerTextBox.Enabled = True
      EmailPasswordButton.Enabled = True
    End If

  End Sub


  Public Sub EmailPassword_OnClick(ByVal sender As Object, ByVal args As EventArgs)

    ' Note: Returning a password in clear text using email is not recommended for
    ' sites that require a high level of security.

    Try
      Dim password As String = Membership.Provider.GetPassword(UsernameTextBox.Text, AnswerTextBox.Text)
      Dim u As MembershipUser = Membership.GetUser(UsernameTextBox.Text)
      EmailPassword(u.Email, password)
      Msg.Text = "Your password was sent via email."
    Catch e As MembershipPasswordException
      Msg.Text = "The password answer is incorrect. Please check the value and try again."
    Catch e As System.Configuration.Provider.ProviderException
      Msg.Text = "An error occurred retrieving your password. Please check your values " & _
                 "and try again."
    End Try

  End Sub


  Private Sub EmailPassword(ByVal email As String, ByVal password As String)

    Try
      Dim Message As MailMessage = New MailMessage("administrator", email)
      Message.Subject = "Your Password"
      Message.Body = "Your password is: " & Server.HtmlEncode(password)
      
      Dim SmtpMail As SmtpClient = New SmtpClient("SMTPSERVER")
      SmtpMail.Send(Message)
    Catch
      Msg.Text = "An exception occurred while sending your password. Please try again."
    End Try

  End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
  <title>Sample: Retrieve Password</title>
</head>
<body>
  <form id="form1" runat="server">
    <h3>
      Retrieve Password</h3>
    <asp:Label ID="Msg" runat="server" ForeColor="maroon" /><br />
    Username:
    <asp:TextBox ID="UsernameTextBox" Columns="30" runat="server" AutoPostBack="True" />
    <asp:RequiredFieldValidator ID="UsernameRequiredValidator" runat="server" ControlToValidate="UsernameTextBox"
      ForeColor="red" Display="Static" ErrorMessage="Required" /><br />
    Password Question: <b>
      <asp:Label ID="QuestionLabel" runat="server" /></b><br />
    Answer:
    <asp:TextBox ID="AnswerTextBox" Columns="60" runat="server" Enabled="False" />
    <asp:RequiredFieldValidator ID="AnswerRequiredValidator" runat="server" ControlToValidate="AnswerTextBox"
      ForeColor="red" Display="Static" ErrorMessage="Required" Enabled="False" /><br />
    <asp:Button ID="EmailPasswordButton" Text="Email My Password" OnClick="EmailPassword_OnClick"
      runat="server" Enabled="False" />
  </form>
</body>
</html>

注解

此方法由Membership类调用,以从 ASP.NET 应用程序的配置文件(web.config)中指定的 SQL Server 数据库中检索用户信息。This method is called by the Membership class to retrieve user information from the SQL Server database specified in the ASP.NET application's configuration file (Web.config).

如果userIsOnlinetrue,则将用户的上次活动日期/时间戳更新为当前日期和时间。If userIsOnline is true, the last activity date/time stamp for the user is updated to the current date and time. 这会反映在LastActivityDateIsOnline属性以及由GetNumberOfUsersOnline返回的值中。This is reflected in the LastActivityDate and IsOnline properties and in the value returned by GetNumberOfUsersOnline.

删除 username 参数值的前导和尾随空格。Leading and trailing spaces are trimmed from the username parameter value.

另请参阅

GetUser(Object, Boolean)

从数据源获得与指定的唯一标识符关联的成员资格用户的信息,并更新该用户的上次活动日期/时间戳(如果指定)。Gets the information from the data source for the membership user associated with the specified unique identifier and updates the last activity date/time stamp for the user, if specified.

public:
 override System::Web::Security::MembershipUser ^ GetUser(System::Object ^ providerUserKey, bool userIsOnline);
public override System.Web.Security.MembershipUser GetUser (object providerUserKey, bool userIsOnline);
override this.GetUser : obj * bool -> System.Web.Security.MembershipUser
Public Overrides Function GetUser (providerUserKey As Object, userIsOnline As Boolean) As MembershipUser

参数

providerUserKey
Object

用户的唯一标识符。The unique identifier for the user.

userIsOnline
Boolean

如果为 true,则更新指定用户的上次活动日期/时间戳;否则为 falsetrue to update the last-activity date/time stamp for the specified user; otherwise, false.

返回

一个 MembershipUser 对象,它表示与指定的唯一标识符关联的用户。A MembershipUser object representing the user associated with the specified unique identifier. 如果在数据库中没有找到指定的 providerUserKey 值所对应的用户,则返回 nullIf no user is found in the database for the specified providerUserKey value, null is returned.

异常

providerUserKeynullproviderUserKey is null.

providerUserKey 的类型不是 GuidproviderUserKey is not of type Guid.

注解

GetUser从数据源检索用户信息,并创建MembershipUser用返回的数据填充的对象。GetUser retrieves the user information from the data source and creates a MembershipUser object populated with the returned data. 用户使用providerUserKey参数指定的唯一标识符进行标识。The user is identified using the unique identifier specified with the providerUserKey parameter.

另请参阅

适用于