.NET Framework Class Library Membership Class Validates user credentials and manages user settings. This class cannot be inherited.

Inheritance Hierarchy
Namespace:
System.Web.Security
Assembly:
System.Web (in System.Web.dll)

Syntax
Public NotInheritable Class Membership
public static class Membership
public ref class Membership abstract sealed
[<AbstractClass>]
[<Sealed>]
type Membership = class end
The Membership type exposes the following members.

Methods
|
| Name | Description |
|---|
.gif) .gif) | CreateUser(String, String) | Adds a new user to the data store. | .gif) .gif) | CreateUser(String, String, String) | Adds a new user with a specified e-mail address to the data store. | .gif) .gif) | 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. | .gif) .gif) | 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. | .gif) .gif) | DeleteUser(String) | Deletes a user and any related user data from the database. | .gif) .gif) | DeleteUser(String, Boolean) | Deletes a user from the database. | .gif) .gif) | FindUsersByEmail(String) | Gets a collection of membership users where the e-mail address contains the specified e-mail address to match. | .gif) .gif) | FindUsersByEmail(String, Int32, Int32, Int32%) | Gets a collection of membership users, in a page of data, where the e-mail address contains the specified e-mail address to match. | .gif) .gif) | FindUsersByName(String) | Gets a collection of membership users where the user name contains the specified user name to match. | .gif) .gif) | FindUsersByName(String, Int32, Int32, Int32%) | Gets a collection of membership users, in a page of data, where the user name contains the specified user name to match. | .gif) .gif) | GeneratePassword | Generates a random password of the specified length. | .gif) .gif) | GetAllUsers()()() | Gets a collection of all the users in the database. | .gif) .gif) | GetAllUsers(Int32, Int32, Int32%) | Gets a collection of all the users in the database in pages of data. | .gif) .gif) | GetNumberOfUsersOnline | Gets the number of users currently accessing an application. | .gif) .gif) | GetUser()()() | Gets the information from the data source and updates the last-activity date/time stamp for the current logged-on membership user. | .gif) .gif) | GetUser(Boolean) | Gets the information from the data source for the current logged-on membership user. Updates the last-activity date/time stamp for the current logged-on membership user, if specified. | .gif) .gif) | GetUser(Object) | Gets the information from the data source for the membership user associated with the specified unique identifier. | .gif) .gif) | GetUser(String) | Gets the information from the data source for the specified membership user. | .gif) .gif) | GetUser(Object, Boolean) | Gets the information from the data source for the membership user associated with the specified unique identifier. Updates the last-activity date/time stamp for the user, if specified. | .gif) .gif) | GetUser(String, Boolean) | Gets the information from the data source for the specified membership user. Updates the last-activity date/time stamp for the user, if specified. | .gif) .gif) | GetUserNameByEmail | Gets a user name where the e-mail address for the user matches the specified e-mail address. | .gif) .gif) | UpdateUser | Updates the database with the information for the specified user. | .gif) .gif) | ValidateUser | Verifies that the supplied user name and password are valid. | Top

Remarks
The Membership class is used in ASP.NET applications to validate user credentials and manage user settings such as passwords and e-mail addresses. The Membership class can be used on its own, or in conjunction with the FormsAuthentication to create a complete system for authenticating users of a Web application or site. The Login control encapsulates the Membership class to provide a convenient mechanism for validating users. The Membership class provides facilities for: Creating new users. Storing membership information (user names, passwords, e-mail addresses, and supporting data) in Microsoft SQL Server or in an alternative data store. Authenticating users who visit your site. You can authenticate users programmatically, or you can use the Login control to create a complete authentication system that requires little or no code. Managing passwords, which includes creating, changing, retrieving, and resetting them, and so on. You can optionally configure ASP.NET membership to require a password question and answer to authenticate password reset or retrieval requests for users that have forgotten their password.
Although ASP.NET membership is a self-standing feature in ASP.NET For authentication, it can be integrated with ASP.NET role management to provide authorization services for your site. Membership can also be integrated with the ASP.NET user System.Web.Profile to provide application-specific customization that can be tailored to individual users. For details, see Understanding Role Management and ASP.NET Profile Properties Overview. The Membership class relies on membership providers to communicate with a data source. The .NET Framework includes a SqlMembershipProvider, which stores user information in a Microsoft SQL Server database, and an ActiveDirectoryMembershipProvider, which enables you to store user information on an Active Directory or Active Directory Application Mode (ADAM) server. You can also implement a custom membership provider to communicate with an alternative data source that can be used by the Membership class. Custom membership providers inherit the MembershipProvider abstract class. For more information, see Implementing a Membership Provider. By default, ASP.NET membership is enabled for all ASP.NET applications. The default membership provider is the SqlMembershipProvider and is specified in the machine configuration with the name AspNetSqlProvider. The default instance of the SqlMembershipProvider is configured to connect to a local instance of Microsoft SQL Server. You can modify the default settings to specify a SqlMembershipProvider other than the AspNetSqlProvider instance as the default provider, or specify an instance of a custom provider as the default provider for your ASP.NET application using the Web.config file. You can specify the ASP.NET membership configuration for your Web application using the membership configuration section in the Web.config file. You can use the providers subsection of the membership section to specify a membership provider other than one of the default providers. For example, the following membership section removes the default membership providers from the current application configuration and adds a new provider with a name of SqlProvider that connects to a SQL Server instance named AspSqlServer.
<configuration>
<connectionStrings>
<add name="SqlServices" connectionString="Data Source=AspSqlServer;Integrated Security=SSPI;Initial Catalog=aspnetdb;" />
</connectionStrings>
<system.web>
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="20">
<providers>
<remove name="AspNetSqlProvider" />
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SqlServices"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
passwordFormat="Hashed"
applicationName="/" />
</providers>
</membership>
</system.web>
</configuration>

Examples
The following code example shows the login page for an ASP.NET application configured to use forms authentication and ASP.NET membership. If the supplied user credentials are invalid, a message is displayed to the user. Otherwise, the user is redirected to the originally requested URL using the RedirectFromLoginPage method. Note |
|---|
The ASP.NET login controls (Login, LoginView, LoginStatus, LoginName, and PasswordRecovery) encapsulate virtually all of the logic required to prompt users for credentials and validate the credentials in the membership system and can be used in place of programmatic checking using the Membership class. |
Security Note |
|---|
This example contains a text box that accepts user input, which is a potential security threat. 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="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 Login_OnClick(sender As Object, args As EventArgs)
If (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text)) Then
FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked)
Else
Msg.Text = "Login failed. Please check your user name and password and try again."
End If
End Sub
</script>
<html >
<head>
<title>Login</title>
</head>
<body>
<form id="form1" runat="server">
<h3>Login</h3>
<asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />
Username: <asp:Textbox id="UsernameTextbox" runat="server" /><br />
Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><br />
<asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />
<asp:CheckBox id="NotPublicCheckBox" runat="server" />
Check here if this is <span style="text-decoration:underline">not</span> a public computer.
</form>
</body>
</html>
<%@ 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 Login_OnClick(object sender, EventArgs args)
{
if (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text))
FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked);
else
Msg.Text = "Login failed. Please check your user name and password and try again.";
}
</script>
<html >
<head>
<title>Login</title>
</head>
<body>
<form id="form1" runat="server">
<h3>Login</h3>
<asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />
Username: <asp:Textbox id="UsernameTextbox" runat="server" /><br />
Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><br />
<asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />
<asp:CheckBox id="NotPublicCheckBox" runat="server" />
Check here if this is <span style="text-decoration:underline">not</span> a public computer.
</form>
</body>
</html>

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
|
Biblioteca de clases de .NET Framework Membership (Clase) Valida las credenciales del usuario y administra su configuración. Esta clase no puede heredarse.

Jerarquía de herencia
Espacio de nombres:
System.Web.Security
Ensamblado:
System.Web (en System.Web.dll)

Sintaxis
Public NotInheritable Class Membership
public static class Membership
public ref class Membership abstract sealed
[<AbstractClass>]
[<Sealed>]
type Membership = class end
El tipo Membership expone los siguientes miembros.

Métodos
|
| Nombre | Descripción |
|---|
.gif) .gif) | CreateUser(String, String) | Agrega un nuevo usuario al origen de datos. | .gif) .gif) | CreateUser(String, String, String) | Agrega a un nuevo usuario con una dirección de correo electrónico especificada al almacén de datos. | .gif) .gif) | CreateUser(String, String, String, String, String, Boolean, MembershipCreateStatus%) | Agrega un nuevo usuario con los valores especificados de las propiedades al almacén de datos y devuelve un parámetro de estado que indica que el usuario se ha creado correctamente o el motivo del error en la creación del usuario. | .gif) .gif) | CreateUser(String, String, String, String, String, Boolean, Object, MembershipCreateStatus%) | Agrega a un nuevo usuario con los valores especificados de las propiedades y un identificador único al almacén de datos y devuelve un parámetro de estado que indica que el usuario se ha creado correctamente o el motivo del error en la creación del usuario. | .gif) .gif) | DeleteUser(String) | Elimina un usuario y cualquier dato del usuario relacionado de la base de datos. | .gif) .gif) | DeleteUser(String, Boolean) | Elimina a un usuario de la base de datos. | .gif) .gif) | FindUsersByEmail(String) | Obtiene una colección de usuarios de pertenencia donde la dirección de correo electrónico contiene la dirección de correo electrónico especificada que debe coincidir. | .gif) .gif) | FindUsersByEmail(String, Int32, Int32, Int32%) | Obtiene una colección de usuarios de pertenencia, en una página de datos donde la dirección de correo electrónico contiene la dirección de correo electrónico especificada que debe coincidir. | .gif) .gif) | FindUsersByName(String) | Obtiene una colección de usuarios de pertenencia donde el nombre de usuario contiene el nombre de usuario especificado para su coincidencia. | .gif) .gif) | FindUsersByName(String, Int32, Int32, Int32%) | Obtiene una colección de usuarios de pertenencia, en una página de datos, cuyo nombre de usuario contiene el nombre de usuario especificado que debe coincidir. | .gif) .gif) | GeneratePassword | Genera una contraseña aleatoria de la longitud especificada. | .gif) .gif) | GetAllUsers()()() | Obtiene una colección de todos los usuarios en la base de datos. | .gif) .gif) | GetAllUsers(Int32, Int32, Int32%) | Obtiene una colección de todos los usuarios de la base de datos en páginas de datos. | .gif) .gif) | GetNumberOfUsersOnline | Obtiene el número de usuarios que actualmente tienen acceso a una aplicación. | .gif) .gif) | GetUser()()() | Recibe la información del origen de datos y actualiza la marca de fecha y hora de la última actividad para el usuario de pertenencia que ha iniciado la sesión. | .gif) .gif) | GetUser(Boolean) | Recibe la información del origen de datos para el usuario de pertenencia que ha iniciado la sesión. Actualiza la marca de fecha y hora de la última actividad para el usuario de pertenencia que ha iniciado la sesión, si se ha especificado. | .gif) .gif) | GetUser(Object) | Recibe la información del origen de datos para el usuario de pertenencia asociado al identificador único especificado. | .gif) .gif) | GetUser(String) | Recibe la información del origen de datos para el usuario de pertenencia especificado. | .gif) .gif) | GetUser(Object, Boolean) | Recibe la información del origen de datos para el usuario de pertenencia asociado al identificador único especificado. Actualiza la marca de fecha y hora de la última actividad para el usuario, si se ha especificado. | .gif) .gif) | GetUser(String, Boolean) | Recibe la información del origen de datos para el usuario de pertenencia especificado. Actualiza la marca de fecha y hora de la última actividad para el usuario, si se ha especificado. | .gif) .gif) | GetUserNameByEmail | Obtiene un nombre de usuario cuya dirección de correo electrónico coincide con la dirección de correo electrónico especificada. | .gif) .gif) | UpdateUser | Actualiza la base de datos con la información correspondiente al usuario especificado. | .gif) .gif) | ValidateUser | Comprueba que el nombre de usuario y la contraseña proporcionados son válidos. | Arriba

Comentarios
La clase Membership se utiliza en aplicaciones ASP.NET para validar las credenciales del usuario y administrar la configuración del usuario como contraseñas y direcciones de correo electrónico. La clase Membership se puede utilizar sola o con la clase FormsAuthentication con objeto de crear un sistema completo para autenticar a los usuarios de una aplicación o sitio Web. El control Login encapsula la clase Membership para proporcionar un mecanismo práctico para validar a los usuarios. La clase Membership proporciona los medios para: Crear nuevos usuarios. Almacenar la información de pertenencia (nombres de usuario, contraseñas, direcciones de correo electrónico y datos compatibles) en Microsoft SQL Server o en un almacén de datos alternativo. Autenticar a los usuarios que visitan el sitio. Mediante programación puede autenticar a los usuarios o puede utilizar el control Login para crear un sistema de autenticación completo que requiere poco o ningún código. Administrar contraseñas que incluyen su creación, cambio, recuperación y restablecimiento, etc. Opcionalmente puede configurar la pertenencia a ASP.NET para que requiera una pregunta y una respuesta de contraseña para autenticar las peticiones de restablecimiento o recuperación de la contraseña para aquellos usuarios que la hayan olvidado.
Aunque la pertenencia a ASP.NET es una característica independiente de ASP.NET para la autenticación, se puede integrar con la administración de funciones de ASP.NET para proporcionar los servicios de la autorización para su sitio. La pertenencia también se puede integrar con el objeto System.Web.Profile del usuario de ASP.NET para proporcionar una personalización específica de la aplicación que se puede diseñar para usuarios individuales. Para obtener información detallada, vea Descripción de la administración de roles y Información general sobre las propiedades de perfil de ASP.NET. La clase Membership confía en proveedores de pertenencia para comunicarse con orígenes de datos. .NET Framework incluye un SqlMembershipProvider, que almacena información de usuario en una base de datos de Microsoft SQL Server, y un ActiveDirectoryMembershipProvider, que le permite almacenar información de usuario en un servidor Active Directory o Active Directory Application Mode (ADAM). También puede implementar un proveedor de pertenencia personalizado para comunicar con un origen de datos alternativo que puede utilizar la clase Membership. Los proveedores de pertenencia personalizados heredan la clase abstracta MembershipProvider. Para obtener más información, vea Implementar un proveedor de pertenencias. De manera predeterminada, la pertenencia a ASP.NET se habilita para todas las aplicaciones ASP.NET. El proveedor de pertenencia predeterminado es la clase SqlMembershipProvider y se especifica en la configuración del equipo con el nombre AspNetSqlProvider. La instancia predeterminada de la clase SqlMembershipProvider se configura para conectar a una instancia local de Microsoft SQL Server. Puede modificar la configuración predeterminada para especificar otra clase SqlMembershipProvider distinta de la instancia de AspNetSqlProvider como el proveedor predeterminado o especifique una instancia de un proveedor personalizado como el proveedor predeterminado para su aplicación ASP.NET utilizando el archivo Web.config. Puede especificar la configuración de pertenencia de ASP.NET para la aplicación Web utilizando la sección de configuración de membership en el archivo Web.config. Puede utilizar la subsección providers de la sección membership para especificar un proveedor de pertenencia distinto de uno de los proveedores predeterminados. Por ejemplo, la sección membership siguiente quita los proveedores de pertenencia predeterminados de la configuración de la aplicación actual y agrega un nuevo proveedor con un nombre de SqlProvider que conecta a una instancia de SQL Server denominada AspSqlServer.
<configuration>
<connectionStrings>
<add name="SqlServices" connectionString="Data Source=AspSqlServer;Integrated Security=SSPI;Initial Catalog=aspnetdb;" />
</connectionStrings>
<system.web>
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="20">
<providers>
<remove name="AspNetSqlProvider" />
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SqlServices"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
passwordFormat="Hashed"
applicationName="/" />
</providers>
</membership>
</system.web>
</configuration>

Ejemplos
En el ejemplo de código siguiente se muestra la página de inicio de sesión para una aplicación ASP.NET configurada para utilizar la autenticación de formularios y la pertenencia ASP.NET. Si las credenciales proporcionadas por el usuario no son válidas, se muestra un mensaje al usuario. De lo contrario, el usuario se redirige a la dirección URL originalmente solicitada mediante el método RedirectFromLoginPage. Nota |
|---|
Los controles de inicio de sesión ASP.NET (Login, LoginView, LoginStatus, LoginNamey PasswordRecovery) encapsulan virtualmente toda la lógica requerida para solicitar las credenciales a los usuarios y validarlas en el sistema de pertenencia y se puede utilizar en lugar de la comprobación de programación mediante la clase Membership. |
Nota sobre la seguridad |
|---|
En este ejemplo hay un cuadro de texto que acepta datos del usuario, lo que puede suponer una amenaza para la seguridad. De forma predeterminada, las páginas web ASP.NET validan los datos escritos por el usuario para comprobar que no incluyen script ni elementos HTML. Para obtener más información, vea Información general sobre los ataques mediante scripts. |
<%@ 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 Login_OnClick(sender As Object, args As EventArgs)
If (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text)) Then
FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked)
Else
Msg.Text = "Login failed. Please check your user name and password and try again."
End If
End Sub
</script>
<html >
<head>
<title>Login</title>
</head>
<body>
<form id="form1" runat="server">
<h3>Login</h3>
<asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />
Username: <asp:Textbox id="UsernameTextbox" runat="server" /><br />
Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><br />
<asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />
<asp:CheckBox id="NotPublicCheckBox" runat="server" />
Check here if this is <span style="text-decoration:underline">not</span> a public computer.
</form>
</body>
</html>
<%@ 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 Login_OnClick(object sender, EventArgs args)
{
if (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text))
FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked);
else
Msg.Text = "Login failed. Please check your user name and password and try again.";
}
</script>
<html >
<head>
<title>Login</title>
</head>
<body>
<form id="form1" runat="server">
<h3>Login</h3>
<asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />
Username: <asp:Textbox id="UsernameTextbox" runat="server" /><br />
Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><br />
<asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />
<asp:CheckBox id="NotPublicCheckBox" runat="server" />
Check here if this is <span style="text-decoration:underline">not</span> a public computer.
</form>
</body>
</html>

Información de versión
.NET FrameworkCompatible con: 4, 3.5, 3.0, 2.0

Plataformas
Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Seguridad para subprocesos
Todos los miembros static ( Shared en Visual Basic) públicos de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Vea también
|