Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

SqlMembershipProvider.CreateUser Method

Adds a new user to the SQL Server membership database.

Namespace:  System.Web.Security
Assembly:  System.Web (in System.Web.dll)
public override MembershipUser CreateUser(
	string username,
	string password,
	string email,
	string passwordQuestion,
	string passwordAnswer,
	bool isApproved,
	Object providerUserKey,
	out MembershipCreateStatus status
)

Parameters

username
Type: System.String

The user name for the new user.

password
Type: System.String

The password for the new user.

email
Type: System.String

The e-mail address for the new user.

passwordQuestion
Type: System.String

The password question for the new user.

passwordAnswer
Type: System.String

The password answer for the new user.

isApproved
Type: System.Boolean

Whether or not the new user is approved to be validated.

providerUserKey
Type: System.Object

A Guid that uniquely identifies the membership user in the SQL Server database.

status
Type: System.Web.Security.MembershipCreateStatus

One of the MembershipCreateStatus values, indicating whether the user was created successfully.

Return Value

Type: System.Web.Security.MembershipUser
A MembershipUser object for the newly created user. If no user was created, this method returns null.

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.

New users are identified with the configured ApplicationName.

If the RequiresUniqueEmail property is set to true, and null or an empty string ("") is specified for the email parameter, the user creation will fail. 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 e-mail address for an existing user in the database for the configured ApplicationName.

The maximum length for the user name is 256 characters. The maximum length for the e-mail address is 256 characters. 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:

  • The password parameter is null, or an empty string after trimming.

  • The length of the password parameter is less than the value specified in the MinRequiredPasswordLength property.

  • The number of non-alphabetic characters in the password parameter is less than the value specified in the MinRequiredNonAlphanumericCharacters property.

  • The password parameter does not pass the regular expression in the PasswordStrengthRegularExpression property.

  • Custom password-validation code canceled user creation during the ValidatingPassword event.

  • The RequiresQuestionAndAnswer property is true and the passwordAnswer parameter is either null or an empty string after trimming.

  • The passwordAnswer parameter is an empty string.

  • The passwordAnswer parameter is longer than 128 characters.

  • The RequiresQuestionAndAnswer property is true and the password question is either null or an empty string after trimming.

  • The passwordQuestion parameter is an empty string.

  • The passwordQuestion parameter is longer than 256 characters.

  • The providerUserKey parameter set to an object of a type other than System.Guid.

  • The providerUserKey parameter is a duplicate of an existing user key.

  • The username parameter is a duplicate of an existing user name.

Leading and trailing spaces are trimmed from all string parameter values.

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.

NoteNote

This sample calls the SqlMembershipProvider specified as the defaultProvider in the Web.config file using the Membership class. If you need to access the default provider as the type SqlMembershipProvider, you can cast the Provider property of the Membership class. 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 e-mail address already exists. Please enter a different e-mail address.";

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

      case MembershipCreateStatus.InvalidEmail:
        return "The e-mail 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>

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.