SqlMembershipProvider.CreateUser(String, String, String, String, String, Boolean, Object, MembershipCreateStatus) 方法

定义

向 SQL Server 成员资格数据库添加一个新用户。Adds a new user to the SQL Server membership database.

public:
 override System::Web::Security::MembershipUser ^ CreateUser(System::String ^ username, System::String ^ password, System::String ^ email, System::String ^ passwordQuestion, System::String ^ passwordAnswer, bool isApproved, System::Object ^ providerUserKey, [Runtime::InteropServices::Out] System::Web::Security::MembershipCreateStatus % status);
public override System.Web.Security.MembershipUser CreateUser (string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status);
override this.CreateUser : string * string * string * string * string * bool * obj * MembershipCreateStatus -> System.Web.Security.MembershipUser
Public Overrides Function CreateUser (username As String, password As String, email As String, passwordQuestion As String, passwordAnswer As String, isApproved As Boolean, providerUserKey As Object, ByRef status As MembershipCreateStatus) As MembershipUser

参数

username
String

新用户的用户名。The user name for the new user.

password
String

新用户的密码。The password for the new user.

email
String

新用户的电子邮件地址。The email address for the new user.

passwordQuestion
String

新用户的密码提示问题。The password question for the new user.

passwordAnswer
String

新用户的密码提示问题答案。The password answer for the new user.

isApproved
Boolean

是否允许验证新用户。Whether or not the new user is approved to be validated.

providerUserKey
Object

唯一标识 SQL Server 数据库中成员资格用户的 GuidA Guid that uniquely identifies the membership user in the SQL Server database.

status
MembershipCreateStatus

一个 MembershipCreateStatus 值,指示是否成功创建用户。One of the MembershipCreateStatus values, indicating whether the user was created successfully.

返回

用于新创建用户的 MembershipUser 对象。A MembershipUser object for the newly created user. 如果没有创建用户,此方法将返回 nullIf no user was created, this method returns null.

示例

下面的代码示例为配置为使用 forms 身份验证和的SqlMembershipProviderASP.NET 应用程序创建一个新用户。The following code example creates a new user for an ASP.NET application configured to use forms authentication and the SqlMembershipProvider. 如果未成功创建用户,则会向用户显示一条消息。If the user is not created successfully, a message is displayed to the user. 否则,会将用户重定向到应用程序的登录页。Otherwise, the user is redirected to the sign-in page for the application.

备注

此示例使用SqlMembershipProvider defaultProviderMembership在 web.config 文件中调用指定的。This sample calls the SqlMembershipProvider specified as the defaultProvider in the Web.config file using the Membership class. 如果需要以类型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" %>
<!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 CreateUser_OnClick(object sender, EventArgs args)
{
  // Create new user and retrieve create status result.

  MembershipCreateStatus status;
  string passwordQuestion = "";
  string passwordAnswer = "";

  if (Membership.RequiresQuestionAndAnswer)
  {
    passwordQuestion = PasswordQuestionTextbox.Text;
    passwordAnswer = PasswordAnswerTextbox.Text;
  }

  try
  {
    MembershipUser newUser = Membership.CreateUser(UsernameTextbox.Text, PasswordTextbox.Text, 
                                                   EmailTextbox.Text, passwordQuestion,
                                                   passwordAnswer, true, out status);
    if (newUser == null)
    {
      Msg.Text = GetErrorMessage(status);
    }
    else
    {
      Response.Redirect("login.aspx");
    }
  }
  catch
  {
    Msg.Text = "An exception occurred creating the user.";
  }
}

public string GetErrorMessage(MembershipCreateStatus status)
{
   switch (status)
   {
      case MembershipCreateStatus.DuplicateUserName:
        return "Username already exists. Please enter a different user name.";

      case MembershipCreateStatus.DuplicateEmail:
        return "A username for that email address already exists. Please enter a different email address.";

      case MembershipCreateStatus.InvalidPassword:
        return "The password provided is invalid. Please enter a valid password value.";

      case MembershipCreateStatus.InvalidEmail:
        return "The email address provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.InvalidAnswer:
        return "The password retrieval answer provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.InvalidQuestion:
        return "The password retrieval question provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.InvalidUserName:
        return "The user name provided is invalid. Please check the value and try again.";

      case MembershipCreateStatus.ProviderError:
        return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

      case MembershipCreateStatus.UserRejected:
        return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

      default:
        return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
   }
}

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Create User</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Create New User</h3>

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

  <table cellpadding="3" border="0">
    <tr>
      <td>Username:</td>
      <td><asp:Textbox id="UsernameTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                      ControlToValidate="UserNameTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td>Password:</td>
      <td><asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /></td>
      <td><asp:RequiredFieldValidator id="PasswordRequiredValidator" runat="server"
                                      ControlToValidate="PasswordTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td>Confirm Password:</td>
      <td><asp:Textbox id="PasswordConfirmTextbox" runat="server" TextMode="Password" /></td>
      <td><asp:RequiredFieldValidator id="PasswordConfirmRequiredValidator" runat="server"
                                      ControlToValidate="PasswordConfirmTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" />
          <asp:CompareValidator id="PasswordConfirmCompareValidator" runat="server"
                                      ControlToValidate="PasswordConfirmTextbox" ForeColor="red"
                                      Display="Static" ControlToCompare="PasswordTextBox"
                                      ErrorMessage="Confirm password must match password." />
      </td>
    </tr>
    <tr>
      <td>Email Address:</td>
      <td><asp:Textbox id="EmailTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="EmailRequiredValidator" runat="server"
                                      ControlToValidate="EmailTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>


<% if (Membership.RequiresQuestionAndAnswer) { %>

    <tr>
      <td>Password Question:</td>
      <td><asp:Textbox id="PasswordQuestionTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="PasswordQuestionRequiredValidator" runat="server"
                                      ControlToValidate="PasswordQuestionTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td>Password Answer:</td>
      <td><asp:Textbox id="PasswordAnswerTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="PasswordAnswerRequiredValidator" runat="server"
                                      ControlToValidate="PasswordAnswerTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>

<% } %>


    <tr>
      <td></td>
      <td><asp:Button id="CreateUserButton" Text="Create User" OnClick="CreateUser_OnClick" runat="server" /></td>
    </tr>
  </table>
</form>

</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Security" %>
<!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 CreateUser_OnClick(sender As Object, args As EventArgs)

  ' Create new user and retrieve create status result.

  Dim status As MembershipCreateStatus
  Dim passwordQuestion As String = ""
  Dim passwordAnswer As String = ""

  If Membership.RequiresQuestionAndAnswer Then
    passwordQuestion = PasswordQuestionTextbox.Text
    passwordAnswer = PasswordAnswerTextbox.Text
  End If

  Try
    Dim newUser As MembershipUser = Membership.CreateUser(UsernameTextbox.Text, PasswordTextbox.Text, _
                                                   EmailTextbox.Text, passwordQuestion, _
                                                   passwordAnswer, True, status)
    If newUser Is Nothing Then
      Msg.Text = GetErrorMessage(status)
    Else
       Response.Redirect("login.aspx")
    End If
  Catch
    Msg.Text = "An exception occurred creating the user."
  End Try

End Sub

Public Function GetErrorMessage(status As MembershipCreateStatus) As String

   Select Case status
   
      Case MembershipCreateStatus.DuplicateUserName:
        Return "Username already exists. Please enter a different user name."

      Case MembershipCreateStatus.DuplicateEmail:
        Return "A username for that email address already exists. Please enter a different email address."

      Case MembershipCreateStatus.InvalidPassword:
        Return "The password provided is invalid. Please enter a valid password value."

      Case MembershipCreateStatus.InvalidEmail:
        Return "The email address provided is invalid. Please check the value and try again."

      Case MembershipCreateStatus.InvalidAnswer:
        Return "The password retrieval answer provided is invalid. Please check the value and try again."

      Case MembershipCreateStatus.InvalidQuestion:
        Return "The password retrieval question provided is invalid. Please check the value and try again."

      Case MembershipCreateStatus.InvalidUserName
        Return "The user name provided is invalid. Please check the value and try again."

      Case MembershipCreateStatus.ProviderError:
        Return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."

      Case MembershipCreateStatus.UserRejected:
        Return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."

      Case Else:
        Return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."
   End Select

End Function

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Create User</title>
</head>
<body>

<form id="form1" runat="server">
  <h3>Create New User</h3>
  <asp:Label id="Msg" ForeColor="maroon" runat="server" />
  <table cellpadding="3" border="0">
    <tr>
      <td>Username:</td>
      <td><asp:Textbox id="UsernameTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                      ControlToValidate="UserNameTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td>Password:</td>
      <td><asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /></td>
      <td><asp:RequiredFieldValidator id="PasswordRequiredValidator" runat="server"
                                      ControlToValidate="PasswordTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td>Confirm Password:</td>
      <td><asp:Textbox id="PasswordConfirmTextbox" runat="server" TextMode="Password" /></td>
      <td><asp:RequiredFieldValidator id="PasswordConfirmRequiredValidator" runat="server"
                                      ControlToValidate="PasswordConfirmTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" />
          <asp:CompareValidator id="PasswordConfirmCompareValidator" runat="server"
                                      ControlToValidate="PasswordConfirmTextbox" ForeColor="red"
                                      Display="Static" ControlToCompare="PasswordTextBox"
                                      ErrorMessage="Confirm password must match password." />
      </td>
    </tr>
    <tr>
      <td>Email Address:</td>
      <td><asp:Textbox id="EmailTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="EmailRequiredValidator" runat="server"
                                      ControlToValidate="EmailTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>


<% If Membership.RequiresQuestionAndAnswer Then %>

    <tr>
      <td>Password Question:</td>
      <td><asp:Textbox id="PasswordQuestionTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="PasswordQuestionRequiredValidator" runat="server"
                                      ControlToValidate="PasswordQuestionTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td>Password Answer:</td>
      <td><asp:Textbox id="PasswordAnswerTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="PasswordAnswerRequiredValidator" runat="server"
                                      ControlToValidate="PasswordAnswerTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>

<% End If %>


    <tr>
      <td></td>
      <td><asp:Button id="CreateUserButton" Text="Create User" OnClick="CreateUser_OnClick" runat="server" /></td>
    </tr>
  </table>
</form>

</body>
</html>

注解

此方法由Membership类调用,以在 ASP.NET 应用程序的配置文件中指定的 SQL Server 数据库中创建新用户。This method is called by the Membership class to create a new user in the SQL Server database specified in the ASP.NET application's configuration file.

新用户用配置ApplicationName的标识。New users are identified with the configured ApplicationName.

如果将true null属性设置为,并且为email参数指定了空字符串(""),则用户创建将失败。 RequiresUniqueEmailIf the RequiresUniqueEmail property is set to true, and null or an empty string ("") is specified for the email parameter, the user creation will fail. 如果RequiresUniqueEmail将属性设置为true ,并且为该email参数指定的值是的配置ApplicationName的数据库中的现有用户的电子邮件地址重复,则用户创建也会失败。The user creation will also fail if the RequiresUniqueEmail property is set to true and the value specified for the email parameter is a duplicate of the email address for an existing user in the database for the configured ApplicationName.

用户名的最大长度为256个字符。The maximum length for the user name is 256 characters. 电子邮件地址的最大长度为256个字符。The maximum length for the email address is 256 characters. 密码的最大长度为明文或哈希或加密之后为128个字符。The maximum length for the password in clear text or after it has been hashed or encrypted is 128 characters.

导致用户创建失败的其他情况:Other conditions that will cause user creation to fail:

  • password参数为null,或修整后出现空字符串。The password parameter is null, or an empty string after trimming.

  • password参数的长度小于在MinRequiredPasswordLength属性中指定的值。The length of the password parameter is less than the value specified in the MinRequiredPasswordLength property.

  • password参数中的非字母字符数小于在MinRequiredNonAlphanumericCharacters属性中指定的值。The number of non-alphabetic characters in the password parameter is less than the value specified in the MinRequiredNonAlphanumericCharacters property.

  • password参数未PasswordStrengthRegularExpression在属性中传递正则表达式。The password parameter does not pass the regular expression in the PasswordStrengthRegularExpression property.

  • 自定义密码验证代码在ValidatingPassword事件期间取消了用户创建。Custom password-validation code canceled user creation during the ValidatingPassword event.

  • 属性为true ,并且passwordAnswer参数为或修整后的空字符串。null RequiresQuestionAndAnswerThe RequiresQuestionAndAnswer property is true and the passwordAnswer parameter is either null or an empty string after trimming.

  • passwordAnswer 参数是空字符串。The passwordAnswer parameter is an empty string.

  • 参数passwordAnswer的长度超过128个字符。The passwordAnswer parameter is longer than 128 characters.

  • 属性为true ,并且密码问题为null或修整后的空字符串。 RequiresQuestionAndAnswerThe RequiresQuestionAndAnswer property is true and the password question is either null or an empty string after trimming.

  • passwordQuestion 参数是空字符串。The passwordQuestion parameter is an empty string.

  • 参数passwordQuestion的长度超过256个字符。The passwordQuestion parameter is longer than 256 characters.

  • 参数设置为类型System.Guid以外的对象。 providerUserKeyThe providerUserKey parameter set to an object of a type other than System.Guid.

  • providerUserKey参数是现有用户密钥的副本。The providerUserKey parameter is a duplicate of an existing user key.

  • username参数与现有用户名重复。The username parameter is a duplicate of an existing user name.

将从所有字符串参数值中去除前导空格和尾随空格。Leading and trailing spaces are trimmed from all string parameter values.

适用于

另请参阅