Membership.CreateUser Metodo

Definizione

Aggiunge un nuovo utente all'archivio dati.

Overload

CreateUser(String, String)

Aggiunge un nuovo utente all'archivio dati.

CreateUser(String, String, String)

Aggiunge all'archivio dati un nuovo utente con l'indirizzo di posta elettronica specificato.

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

Aggiunge all'archivio dati un nuovo utente con valori di proprietà specifici e restituisce un parametro di stato che indica se l'utente è stato creato correttamente. In caso contrario, riporta il motivo per cui la creazione dell'utente non è riuscita.

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

Aggiunge all'archivio dati un nuovo utente con valori di proprietà specifici e un identificatore univoco, oltre a restituire un parametro di stato che indica se l'utente è stato creato correttamente. In caso contrario, riporta il motivo per cui la creazione dell'utente non è riuscita.

CreateUser(String, String)

Aggiunge un nuovo utente all'archivio dati.

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

Parametri

username
String

Nome utente per il nuovo utente.

password
String

Password per il nuovo utente.

Restituisce

MembershipUser

Oggetto MembershipUser per l'utente appena creato.

Eccezioni

L'utente non è stato creato. Verificare nella proprietà StatusCode la presenza di un valore MembershipCreateStatus.

Esempio

Nell'esempio di codice seguente viene creato un nuovo utente per un'applicazione ASP.NET configurata per usare l'autenticazione dei moduli e l'appartenenza ASP.NET. Se l'utente non viene creato correttamente, viene visualizzato un messaggio all'utente. In caso contrario, l'utente viene reindirizzato alla pagina di accesso per l'applicazione.

Importante

Questo esempio contiene una casella di testo che accetta l'input utente, ovvero una potenziale minaccia di sicurezza. Per impostazione predefinita, le pagine Web ASP.NET verificano che l'input dell'utente non includa script o elementi HTML. Per altre informazioni, vedere Cenni preliminari sugli attacchi tramite script.

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

Commenti

CreateUser aggiunge un nuovo utente all'archivio dati e restituisce un MembershipUser oggetto per l'utente appena creato. Se la creazione dell'utente ha esito negativo, viene generata una MembershipCreateUserException classe. È possibile recuperare un MembershipCreateStatus valore dalla StatusCode proprietà dell'oggetto MembershipCreateUserException che indica perché la creazione dell'utente non è riuscita.

Dopo aver creato un utente di appartenenza e si dispone di un riferimento a un MembershipUser oggetto per tale utente, è possibile modificare le impostazioni per tale utente con MembershipUser i metodi pubblici, ad esempio ChangePasswordQuestionAndAnswer per le applicazioni in cui RequiresQuestionAndAnswer è trueo impostando i valori delle proprietà dell'oggetto MembershipUser e passandoli al UpdateUser metodo.

Se un utente esiste già nell'origine dati per l'applicazione, è possibile ottenere un MembershipUser oggetto per l'utente esistente con il GetUser metodo .

Fornisce SqlMembershipProvider un'opzione per richiedere un indirizzo di posta elettronica univoco per ogni utente. Se la RequiresUniqueEmail proprietà è true, è necessario usare uno degli CreateUser overload che consente di specificare un indirizzo di posta elettronica per l'utente creato. In caso contrario, verrà generata una MembershipCreateUserException classe.

Gli spazi iniziali e finali vengono tagliati da tutti i valori dei parametri.

Vedi anche

Si applica a

CreateUser(String, String, String)

Aggiunge all'archivio dati un nuovo utente con l'indirizzo di posta elettronica specificato.

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

Parametri

username
String

Nome utente per il nuovo utente.

password
String

Password per il nuovo utente.

email
String

Indirizzo di posta elettronica del nuovo utente.

Restituisce

MembershipUser

Oggetto MembershipUser per l'utente appena creato.

Eccezioni

L'utente non è stato creato. Verificare nella proprietà StatusCode la presenza di un valore MembershipCreateStatus.

Esempio

Nell'esempio di codice seguente viene creato un nuovo utente per un'applicazione ASP.NET configurata per usare l'autenticazione dei moduli e l'appartenenza ASP.NET. Se l'utente non viene creato correttamente, viene visualizzato un messaggio all'utente. In caso contrario, l'utente viene reindirizzato alla pagina di accesso per l'applicazione.

Importante

Questo esempio contiene una casella di testo che accetta l'input utente, ovvero una potenziale minaccia di sicurezza. Per impostazione predefinita, le pagine Web ASP.NET verificano che l'input dell'utente non includa script o elementi HTML. Per altre informazioni, vedere Cenni preliminari sugli attacchi tramite script.

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

Commenti

CreateUser aggiunge un nuovo utente all'archivio dati e restituisce un MembershipUser oggetto per l'utente appena creato. Se la creazione dell'utente ha esito negativo, viene generata una MembershipCreateUserException classe. È possibile recuperare un MembershipCreateStatus valore dalla StatusCode proprietà dell'oggetto MembershipCreateUserException che indica perché la creazione dell'utente non è riuscita.

Dopo aver creato un utente di appartenenza e si dispone di un riferimento a un MembershipUser oggetto per tale utente, è possibile modificare le impostazioni per tale utente con MembershipUser i metodi pubblici, ad esempio ChangePasswordQuestionAndAnswer per le applicazioni in cui RequiresQuestionAndAnswer è trueo impostando i valori delle proprietà dell'oggetto MembershipUser e passandoli al UpdateUser metodo.

Se un utente esiste già nell'origine dati per l'applicazione, è possibile ottenere un MembershipUser oggetto per l'utente esistente con il GetUser metodo .

Gli spazi iniziali e finali vengono tagliati da tutti i valori dei parametri.

Vedi anche

Si applica a

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

Aggiunge all'archivio dati un nuovo utente con valori di proprietà specifici e restituisce un parametro di stato che indica se l'utente è stato creato correttamente. In caso contrario, riporta il motivo per cui la creazione dell'utente non è riuscita.

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 * MembershipCreateStatus -> 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

Parametri

username
String

Nome utente per il nuovo utente.

password
String

Password per il nuovo utente.

email
String

Indirizzo di posta elettronica del nuovo utente.

passwordQuestion
String

Domanda per la password dell'utente di appartenenza.

passwordAnswer
String

Risposta per la password dell'utente di appartenenza.

isApproved
Boolean

Parametro booleano che stabilisce se il nuovo utente è autorizzato ad accedere al sistema.

status
MembershipCreateStatus

Oggetto MembershipCreateStatus che indica se l'utente è stato creato correttamente o, in caso contrario, il motivo per cui la creazione ha avuto esito negativo.

Restituisce

MembershipUser

Oggetto MembershipUser per l'utente appena creato. Se non è stato creato alcun utente, il metodo restituisce il valore null.

Esempio

Nell'esempio di codice seguente viene creato un nuovo utente per un'applicazione ASP.NET configurata per l'uso dell'autenticazione basata su form e dell'appartenenza ASP.NET. Se l'utente non viene creato correttamente, viene visualizzato un messaggio all'utente. In caso contrario, l'utente viene reindirizzato alla pagina di accesso per l'applicazione.

Importante

Questo esempio contiene una casella di testo che accetta l'input dell'utente, che rappresenta una potenziale minaccia per la sicurezza. Per impostazione predefinita, le pagine Web ASP.NET verificano che l'input dell'utente non includa script o elementi HTML. Per altre informazioni, vedere Cenni preliminari sugli attacchi tramite script.

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

Commenti

CreateUser aggiunge un nuovo utente all'archivio dati e restituisce un MembershipUser oggetto per l'utente appena creato. Se la creazione dell'utente non riesce, è possibile recuperare un MembershipCreateStatus valore dal status parametro di output che indica il motivo per cui la creazione dell'utente non è riuscita.

Il CreateUser metodo restituirà null se password è una stringa vuota o null, username è una stringa vuota o null contiene una virgola (,), passwordQuestion non null è e è una stringa vuota o passwordAnswer non null è e contiene una stringa vuota.

Dopo aver creato un utente di appartenenza e aver ottenuto un riferimento a un MembershipUser oggetto per tale utente, è possibile modificare le impostazioni per tale utente con i MembershipUser metodi pubblici e impostando i valori delle proprietà dell'oggetto MembershipUser e quindi passando l'oggetto MembershipUser al UpdateUser metodo .

Se un utente esiste già nell'origine dati per l'applicazione, è possibile ottenere un MembershipUser oggetto per l'utente esistente con il GetUser metodo .

Gli spazi iniziali e finali vengono eliminati da tutti i valori dei parametri stringa.

Vedi anche

Si applica a

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

Aggiunge all'archivio dati un nuovo utente con valori di proprietà specifici e un identificatore univoco, oltre a restituire un parametro di stato che indica se l'utente è stato creato correttamente. In caso contrario, riporta il motivo per cui la creazione dell'utente non è riuscita.

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 * MembershipCreateStatus -> 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

Parametri

username
String

Nome utente per il nuovo utente.

password
String

Password per il nuovo utente.

email
String

Indirizzo di posta elettronica del nuovo utente.

passwordQuestion
String

Domanda per la password dell'utente di appartenenza.

passwordAnswer
String

Risposta per la password dell'utente di appartenenza.

isApproved
Boolean

Parametro booleano che stabilisce se il nuovo utente è autorizzato ad accedere al sistema.

providerUserKey
Object

Identificatore dell'utente da memorizzare nell'archivio dati di appartenenze.

status
MembershipCreateStatus

Oggetto MembershipCreateStatus che indica se l'utente è stato creato correttamente o, in caso contrario, il motivo per cui la creazione ha avuto esito negativo.

Restituisce

MembershipUser

Oggetto MembershipUser per l'utente appena creato. Se non è stato creato alcun utente, il metodo restituisce il valore null.

Commenti

CreateUser aggiunge un nuovo utente all'archivio dati e restituisce un MembershipUser oggetto per l'utente appena creato. Se la creazione dell'utente non riesce, è possibile recuperare un MembershipCreateStatus valore dal status parametro di output che indica il motivo per cui la creazione dell'utente non è riuscita. È possibile specificare un identificatore univoco per l'utente, ad esempio un valore di chiave primaria per un database, usando il providerUserKey parametro .

Il CreateUser metodo restituirà null se password è una stringa vuota o null, username è una stringa vuota o null contiene una virgola (,), passwordQuestion non null è e contiene una stringa vuota o passwordAnswer non null è e contiene una stringa vuota.

Dopo aver creato un utente di appartenenza e aver ottenuto un riferimento a un MembershipUser oggetto per tale utente, è possibile modificare le impostazioni per tale utente con i MembershipUser metodi pubblici e impostando i valori delle proprietà dell'oggetto MembershipUser e quindi passando l'oggetto MembershipUser al UpdateUser metodo .

Se un utente esiste già nell'origine dati per l'applicazione, è possibile ottenere un MembershipUser oggetto per l'utente esistente con il GetUser metodo .

Gli spazi iniziali e finali vengono eliminati da tutti i valori dei parametri stringa.

Vedi anche

Si applica a