Membership.CreateUser Membership.CreateUser Membership.CreateUser Membership.CreateUser Method

Определение

Добавляет нового пользователя в хранилище данных.Adds a new user to the data store.

Перегрузки

CreateUser(String, String) CreateUser(String, String) CreateUser(String, String) CreateUser(String, String)

Добавляет нового пользователя в хранилище данных.Adds a new user to the data store.

CreateUser(String, String, String) CreateUser(String, String, String) CreateUser(String, String, String) CreateUser(String, String, String)

Добавляет в хранилище данных нового пользователя с указанным адресом электронной почты.Adds a new user with a specified email address to the data store.

CreateUser(String, String, String, String, String, Boolean, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, MembershipCreateStatus)

Добавляет в хранилище данных нового пользователя со значениями указанного свойства и возвращает параметр состояния, который сообщает об успешном создании пользователя или содержит причину, по которой не удалось создать пользователя.Adds a new user with specified property values to the data store and returns a status parameter indicating that the user was successfully created or the reason the user creation failed.

CreateUser(String, String, String, String, String, Boolean, Object, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, Object, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, Object, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, Object, MembershipCreateStatus)

Добавляет в хранилище данных нового пользователя со значениями указанного свойства и уникальным идентификатором, и возвращает параметр состояния, который сообщает об успешном создании пользователя или содержит причину, по которой не удалось создать пользователя.Adds a new user with specified property values and a unique identifier to the data store and returns a status parameter indicating that the user was successfully created or the reason the user creation failed.

CreateUser(String, String) CreateUser(String, String) CreateUser(String, String) CreateUser(String, String)

Добавляет нового пользователя в хранилище данных.Adds a new user to the data store.

public:
 static System::Web::Security::MembershipUser ^ CreateUser(System::String ^ username, System::String ^ password);
public static System.Web.Security.MembershipUser CreateUser (string username, string password);
static member CreateUser : string * string -> System.Web.Security.MembershipUser
Public Shared Function CreateUser (username As String, password As String) As MembershipUser

Параметры

username
String String String String

Имя пользователя для нового пользователя.The user name for the new user.

password
String String String String

Пароль для нового пользователя.The password for the new user.

Возвраты

Объект MembershipUser для вновь созданного пользователя.A MembershipUser object for the newly created user.

Исключения

Пользователь не был создан.The user was not created. Проверьте свойство StatusCode для значения MembershipCreateStatus.Check the StatusCode property for a MembershipCreateStatus value.

Примеры

В следующем примере кода создает нового пользователя для приложения ASP.NET, настроены на использование проверки подлинности форм и членства ASP.NET.The following code example creates a new user for an ASP.NET application configured to use forms authentication and ASP.NET membership. Если пользователь не создан успешно, отображается сообщение для пользователя.If the user is not created successfully, a message is displayed to the user. В противном случае пользователь перенаправляется на страницу входа для приложения.Otherwise, the user is redirected to the login page for the application.

Важно!

В этом примере содержит текстовое поле ввода данных пользователя, который является потенциальной угрозой безопасности.This example contains a text box that accepts user input, which is a potential security threat. По умолчанию данные, вводимые пользователем на веб-страницах ASP.NET, проверяются на наличие скриптов и HTML-элементов.By default, ASP.NET Web pages validate that user input does not include script or HTML elements. Дополнительные сведения см. в разделе Общие сведения об использовании сценариев.For more information, see Script Exploits Overview.

<%@ 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)
{
  try
  {
    // Create new user.

    MembershipUser newUser = Membership.CreateUser(UsernameTextbox.Text, PasswordTextbox.Text);


    // If user created successfully, set password question and answer (if applicable) and 
    // redirect to login page. Otherwise return an error message.

    if (Membership.RequiresQuestionAndAnswer)
    {
      newUser.ChangePasswordQuestionAndAnswer(PasswordTextbox.Text,
                                              PasswordQuestionTextbox.Text,
                                              PasswordAnswerTextbox.Text);
    }

    Response.Redirect("login.aspx");
  }
  catch (MembershipCreateUserException e)
  {
    Msg.Text = GetErrorMessage(e.StatusCode);
  }
  catch (HttpException e)
  {
    Msg.Text = e.Message;
  }
}

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>


<% 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)
  Try
    ' Create new user.

    Dim newUser As MembershipUser = Membership.CreateUser(UsernameTextbox.Text, PasswordTextbox.Text)


    ' If user created successfully, set password question and answer (if applicable) and 
    ' redirect to login page. Otherwise Return an error message.

    If Membership.RequiresQuestionAndAnswer Then
    
      newUser.ChangePasswordQuestionAndAnswer(PasswordTextbox.Text, _
                                              PasswordQuestionTextbox.Text, _
                                              PasswordAnswerTextbox.Text)
    End If

    Response.Redirect("login.aspx")
  Catch e As MembershipCreateUserException
    Msg.Text = GetErrorMessage(e.StatusCode)
  Catch e As HttpException
    Msg.Text = e.Message
  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" /><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>


<% 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>

Комментарии

CreateUser Добавляет нового пользователя в хранилище данных и возвращает MembershipUser объект для только что созданного пользователя.CreateUser adds a new user to the data store and returns a MembershipUser object for the newly created user. Если не удается создать пользователя, MembershipCreateUserException возникает исключение.If the user creation fails, a MembershipCreateUserException is thrown. Вы можете получить MembershipCreateStatus значение из StatusCode свойство MembershipCreateUserException , указывающее, почему не удалось создать пользователя.You can retrieve a MembershipCreateStatus value from the StatusCode property of the MembershipCreateUserException that indicates why user creation failed.

После того как пользователь членства был создан и иметь ссылку на MembershipUser объекта для этого пользователя, можно изменить параметры для этого пользователя с MembershipUser открытые методы, такие как ChangePasswordQuestionAndAnswer для приложений, где RequiresQuestionAndAnswer является true, или установив значения свойств MembershipUser объекта и передачи их UpdateUser метод.Once a membership user has been created and you have a reference to a MembershipUser object for that user, you can modify the settings for that user with the MembershipUser public methods, such as ChangePasswordQuestionAndAnswer for applications where RequiresQuestionAndAnswer is true, or by setting the property values of the MembershipUser object and passing them to the UpdateUser method.

Если пользователь уже существует в источнике данных для приложения, можно получить MembershipUser для существующего пользователя с GetUser метод.If a user already exists in the data source for the application, you can obtain a MembershipUser object for the existing user with the GetUser method.

SqlMembershipProvider Предоставляет параметр, чтобы требовать уникальный адрес электронной почты для каждого пользователя.The SqlMembershipProvider provides an option to require a unique email address for each user. Если RequiresUniqueEmail свойство true, необходимо будет использовать один из CreateUser перегрузки, которые можно указать адрес электронной почты для создания пользователя.If the RequiresUniqueEmail property is true, you will need to use one of the CreateUser overloads that allows you to specify an email address for the user being created. В противном случае MembershipCreateUserException будет создано.Otherwise, a MembershipCreateUserException will be thrown.

Начальные и конечные пробелы удаляются из значения всех параметров.Leading and trailing spaces are trimmed from all parameter values.

Дополнительно

CreateUser(String, String, String) CreateUser(String, String, String) CreateUser(String, String, String) CreateUser(String, String, String)

Добавляет в хранилище данных нового пользователя с указанным адресом электронной почты.Adds a new user with a specified email address to the data store.

public:
 static System::Web::Security::MembershipUser ^ CreateUser(System::String ^ username, System::String ^ password, System::String ^ email);
public static System.Web.Security.MembershipUser CreateUser (string username, string password, string email);
static member CreateUser : string * string * string -> System.Web.Security.MembershipUser
Public Shared Function CreateUser (username As String, password As String, email As String) As MembershipUser

Параметры

username
String String String String

Имя пользователя для нового пользователя.The user name for the new user.

password
String String String String

Пароль для нового пользователя.The password for the new user.

email
String String String String

Адрес электронной почты для нового пользователя.The email address for the new user.

Возвраты

Объект MembershipUser для вновь созданного пользователя.A MembershipUser object for the newly created user.

Исключения

Пользователь не был создан.The user was not created. Проверьте свойство StatusCode для значения MembershipCreateStatus.Check the StatusCode property for a MembershipCreateStatus value.

Примеры

В следующем примере кода создает нового пользователя для приложения ASP.NET, настроены на использование проверки подлинности форм и членства ASP.NET.The following code example creates a new user for an ASP.NET application configured to use forms authentication and ASP.NET membership. Если пользователь не создан успешно, отображается сообщение для пользователя.If the user is not created successfully, a message is displayed to the user. В противном случае пользователь перенаправляется на страницу входа для приложения.Otherwise, the user is redirected to the login page for the application.

Важно!

В этом примере содержит текстовое поле ввода данных пользователя, который является потенциальной угрозой безопасности.This example contains a text box that accepts user input, which is a potential security threat. По умолчанию данные, вводимые пользователем на веб-страницах ASP.NET, проверяются на наличие скриптов и HTML-элементов.By default, ASP.NET Web pages validate that user input does not include script or HTML elements. Дополнительные сведения см. в разделе Общие сведения об использовании сценариев.For more information, see Script Exploits Overview.

<%@ 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)
{
  MembershipCreateStatus result;

  try
  {
    // Create new user.

    if (Membership.RequiresQuestionAndAnswer)
    {
      MembershipUser newUser = Membership.CreateUser(
        UsernameTextbox.Text, 
        PasswordTextbox.Text, 
        EmailTextbox.Text,
        PasswordQuestionTextbox.Text,
        PasswordAnswerTextbox.Text,
        false,
        out result);
    }
    else 
    {
      MembershipUser newUser = Membership.CreateUser(
        UsernameTextbox.Text, 
        PasswordTextbox.Text, 
        EmailTextbox.Text);
    }

    Response.Redirect("login.aspx");
  }
  catch (MembershipCreateUserException e)
  {
    Msg.Text = GetErrorMessage(e.StatusCode);
  }
  catch (HttpException e)
  {
    Msg.Text = e.Message;
  }
}

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)
  Dim result As MembershipCreateStatus
  Try
    ' Create new user.

    Dim newUser As MembershipUser
    If Membership.RequiresQuestionAndAnswer Then
      newUser  = Membership.CreateUser( _
        UsernameTextbox.Text, _
        PasswordTextbox.Text, _
        EmailTextbox.Text, _
        PasswordQuestionTextbox.Text, _
        PasswordAnswerTextbox.Text, _
        false, _
        result)
    Else
      newUser  = Membership.CreateUser( _
        UsernameTextbox.Text, _
        PasswordTextbox.Text, _
        EmailTextbox.Text)
    End If

    Response.Redirect("login.aspx")

  Catch e As MembershipCreateUserException
    Msg.Text = GetErrorMessage(e.StatusCode)
  Catch e As HttpException
    Msg.Text = e.Message
  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" /><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 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>

Комментарии

CreateUser Добавляет нового пользователя в хранилище данных и возвращает MembershipUser объект для только что созданного пользователя.CreateUser adds a new user to the data store and returns a MembershipUser object for the newly created user. Если не удается создать пользователя, MembershipCreateUserException возникает исключение.If the user creation fails, a MembershipCreateUserException is thrown. Вы можете получить MembershipCreateStatus значение из StatusCode свойство MembershipCreateUserException , указывающее, почему не удалось создать пользователя.You can retrieve a MembershipCreateStatus value from the StatusCode property of the MembershipCreateUserException that indicates why user creation failed.

После того как пользователь членства был создан и иметь ссылку на MembershipUser объекта для этого пользователя, можно изменить параметры для этого пользователя с MembershipUser открытые методы, такие как ChangePasswordQuestionAndAnswer для приложений, где RequiresQuestionAndAnswer является true, или установив значения свойств MembershipUser объекта и передачи их UpdateUser метод.Once a membership user has been created and you have a reference to a MembershipUser object for that user, you can modify the settings for that user with the MembershipUser public methods, such as ChangePasswordQuestionAndAnswer for applications where RequiresQuestionAndAnswer is true, or by setting the property values of the MembershipUser object and passing them to the UpdateUser method.

Если пользователь уже существует в источнике данных для приложения, можно получить MembershipUser для существующего пользователя с GetUser метод.If a user already exists in the data source for the application, you can obtain a MembershipUser object for the existing user with the GetUser method.

Начальные и конечные пробелы удаляются из значения всех параметров.Leading and trailing spaces are trimmed from all parameter values.

Дополнительно

CreateUser(String, String, String, String, String, Boolean, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, MembershipCreateStatus)

Добавляет в хранилище данных нового пользователя со значениями указанного свойства и возвращает параметр состояния, который сообщает об успешном создании пользователя или содержит причину, по которой не удалось создать пользователя.Adds a new user with specified property values to the data store and returns a status parameter indicating that the user was successfully created or the reason the user creation failed.

public:
 static System::Web::Security::MembershipUser ^ CreateUser(System::String ^ username, System::String ^ password, System::String ^ email, System::String ^ passwordQuestion, System::String ^ passwordAnswer, bool isApproved, [Runtime::InteropServices::Out] System::Web::Security::MembershipCreateStatus % status);
public static System.Web.Security.MembershipUser CreateUser (string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, out System.Web.Security.MembershipCreateStatus status);
static member CreateUser : string * string * string * string * string * bool *  -> System.Web.Security.MembershipUser
Public Shared Function CreateUser (username As String, password As String, email As String, passwordQuestion As String, passwordAnswer As String, isApproved As Boolean, ByRef status As MembershipCreateStatus) As MembershipUser

Параметры

username
String String String String

Имя пользователя для нового пользователя.The user name for the new user.

password
String String String String

Пароль для нового пользователя.The password for the new user.

email
String String String String

Адрес электронной почты для нового пользователя.The email address for the new user.

passwordQuestion
String String String String

Значение контрольного вопроса для пользователя членства.The password-question value for the membership user.

passwordAnswer
String String String String

Значение ответа на контрольный вопрос для пользователя членства.The password-answer value for the membership user.

isApproved
Boolean Boolean Boolean Boolean

Логическое значение, указывающее одобрен ли вход пользователя в систему.A Boolean that indicates whether the new user is approved to log on.

status
MembershipCreateStatus MembershipCreateStatus MembershipCreateStatus MembershipCreateStatus

Класс MembershipCreateStatus, который сообщает об успешном создании пользователя или содержит причину, по которой не удалось создать пользователя.A MembershipCreateStatus indicating that the user was created successfully or the reason that creation failed.

Возвраты

Объект MembershipUser для вновь созданного пользователя.A MembershipUser object for the newly created user. Если пользователь не был создан, метод возвращает значение null.If no user was created, this method returns null.

Примеры

В следующем примере кода создает нового пользователя для приложения ASP.NET, настроены на использование проверки подлинности форм и членства ASP.NET.The following code example creates a new user for an ASP.NET application configured to use forms authentication and ASP.NET membership. Если пользователь не создан успешно, отображается сообщение для пользователя.If the user is not created successfully, a message is displayed to the user. В противном случае пользователь перенаправляется на страницу входа для приложения.Otherwise, the user is redirected to the login page for the application.

Важно!

В этом примере содержит текстовое поле ввода данных пользователя, который является потенциальной угрозой безопасности.This example contains a text box that accepts user input, which is a potential security threat. По умолчанию данные, вводимые пользователем на веб-страницах ASP.NET, проверяются на наличие скриптов и HTML-элементов.By default, ASP.NET Web pages validate that user input does not include script or HTML elements. Дополнительные сведения см. в разделе Общие сведения об использовании сценариев.For more information, see Script Exploits Overview.

<%@ 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>

Комментарии

CreateUser Добавляет нового пользователя в хранилище данных и возвращает MembershipUser объект для только что созданного пользователя.CreateUser adds a new user to the data store and returns a MembershipUser object for the newly created user. Если не удается создать пользователя, можно получить MembershipCreateStatus значение из status выходной параметр, который указывает, почему не удалось создать пользователя.If the user creation fails, you can retrieve a MembershipCreateStatus value from the status output parameter that indicates why user creation failed.

CreateUser Метод возвратит null Если password является пустой строкой или null, username является пустой строкой или null или содержит запятую (,), passwordQuestion не null и является пустой строкой, или passwordAnswer не null и содержит пустую строку.The CreateUser method will return null if password is an empty string or null, username is an empty string or null or contains a comma (,), passwordQuestion is not null and is an empty string, or passwordAnswer is not null and contains an empty string.

После того как пользователь членства был создан и иметь ссылку на MembershipUser объекта для этого пользователя, можно изменить параметры для этого пользователя с MembershipUser открытые методы и задавая значения свойств из MembershipUser объекта и передав MembershipUser объект UpdateUser метод.Once a membership user has been created and you have a reference to a MembershipUser object for that user, you can modify the settings for that user with the MembershipUser public methods and by setting the property values of the MembershipUser object and then passing the MembershipUser object to the UpdateUser method.

Если пользователь уже существует в источнике данных для приложения, можно получить MembershipUser для существующего пользователя с GetUser метод.If a user already exists in the data source for the application, you can obtain a MembershipUser object for the existing user with the GetUser method.

Начальные и конечные пробелы удаляются из значений всех строковых параметров.Leading and trailing spaces are trimmed from all string parameter values.

Дополнительно

CreateUser(String, String, String, String, String, Boolean, Object, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, Object, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, Object, MembershipCreateStatus) CreateUser(String, String, String, String, String, Boolean, Object, MembershipCreateStatus)

Добавляет в хранилище данных нового пользователя со значениями указанного свойства и уникальным идентификатором, и возвращает параметр состояния, который сообщает об успешном создании пользователя или содержит причину, по которой не удалось создать пользователя.Adds a new user with specified property values and a unique identifier to the data store and returns a status parameter indicating that the user was successfully created or the reason the user creation failed.

public:
 static 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 static 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);
static member CreateUser : string * string * string * string * string * bool * obj *  -> System.Web.Security.MembershipUser
Public Shared 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 String String String

Имя пользователя для нового пользователя.The user name for the new user.

password
String String String String

Пароль для нового пользователя.The password for the new user.

email
String String String String

Адрес электронной почты для нового пользователя.The email address for the new user.

passwordQuestion
String String String String

Значение контрольного вопроса для пользователя членства.The password-question value for the membership user.

passwordAnswer
String String String String

Значение ответа на контрольный вопрос для пользователя членства.The password-answer value for the membership user.

isApproved
Boolean Boolean Boolean Boolean

Логическое значение, указывающее одобрен ли вход пользователя в систему.A Boolean that indicates whether the new user is approved to log on.

providerUserKey
Object Object Object Object

Идентификатор пользователя для пользователя, который должен быть сохранен в хранилище данных участия.The user identifier for the user that should be stored in the membership data store.

status
MembershipCreateStatus MembershipCreateStatus MembershipCreateStatus MembershipCreateStatus

Класс MembershipCreateStatus, который сообщает об успешном создании пользователя или содержит причину, по которой не удалось создать пользователя.A MembershipCreateStatus indicating that the user was created successfully or the reason creation failed.

Возвраты

Объект MembershipUser для вновь созданного пользователя.A MembershipUser object for the newly created user. Если пользователь не был создан, метод возвращает значение null.If no user was created, this method returns null.

Комментарии

CreateUser Добавляет нового пользователя в хранилище данных и возвращает MembershipUser объект для только что созданного пользователя.CreateUser adds a new user to the data store and returns a MembershipUser object for the newly created user. Если не удается создать пользователя, можно получить MembershipCreateStatus значение из status выходной параметр, который указывает, почему не удалось создать пользователя.If the user creation fails, you can retrieve a MembershipCreateStatus value from the status output parameter that indicates why user creation failed. Уникальный идентификатор для пользователя, например значение первичного ключа для базы данных, можно указать с помощью providerUserKey параметра.You can specify a unique identifier for the user, such as a primary key value for a database, by using the providerUserKey parameter.

CreateUser Метод возвратит null Если password является пустой строкой или null, username является пустой строкой или null или содержит запятую (,), passwordQuestion не null и содержит пустой Строка, или passwordAnswer не null и содержит пустую строку.The CreateUser method will return null if password is an empty string or null, username is an empty string or null or contains a comma (,), passwordQuestion is not null and contains an empty string, or passwordAnswer is not null and contains an empty string.

После того как пользователь членства был создан и иметь ссылку на MembershipUser объекта для этого пользователя, можно изменить параметры для этого пользователя с MembershipUser открытые методы и задавая значения свойств из MembershipUser объекта и передав MembershipUser объект UpdateUser метод.Once a membership user has been created and you have a reference to a MembershipUser object for that user, you can modify the settings for that user with the MembershipUser public methods and by setting the property values of the MembershipUser object and then passing the MembershipUser object to the UpdateUser method.

Если пользователь уже существует в источнике данных для приложения, можно получить MembershipUser для существующего пользователя с GetUser метод.If a user already exists in the data source for the application, you can obtain a MembershipUser object for the existing user with the GetUser method.

Начальные и конечные пробелы удаляются из значений всех строковых параметров.Leading and trailing spaces are trimmed from all string parameter values.

Дополнительно

Применяется к