.NET Framework Class Library Login Class Provides user interface (UI) elements for logging in to a Web site.

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

Syntax
<BindableAttribute(False)> _
Public Class Login _
Inherits CompositeControl
[BindableAttribute(false)]
public class Login : CompositeControl
[BindableAttribute(false)]
public ref class Login : public CompositeControl
[<BindableAttribute(false)>]
type Login =
class
inherit CompositeControl
end
The Login type exposes the following members.

Constructors
|
| Name | Description |
|---|
.gif) | Login | Creates a new instance of the Login control. | Top

Methods
|
| Name | Description |
|---|
.gif) | AddAttributesToRender | Adds HTML attributes and styles that need to be rendered to the specified HtmlTextWriterTag. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | AddedControl | Called after a child control is added to the Controls collection of the Control object. (Inherited from Control.) | .gif) | AddParsedSubObject | Notifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's ControlCollection object. (Inherited from Control.) | .gif) | ApplyStyle | Copies any nonblank elements of the specified style to the Web control, overwriting any existing style elements of the control. This method is primarily used by control developers. (Inherited from WebControl.) | .gif) | ApplyStyleSheetSkin | Applies the style properties defined in the page style sheet to the control. (Inherited from Control.) | .gif) | BuildProfileTree | Infrastructure. Gathers information about the server control and delivers it to the Trace property to be displayed when tracing is enabled for the page. (Inherited from Control.) | .gif) | ClearCachedClientID | Infrastructure. Sets the cached ClientID value to nullNothingnullptra null reference (Nothing in Visual Basic). (Inherited from Control.) | .gif) | ClearChildControlState | Deletes the control-state information for the server control's child controls. (Inherited from Control.) | .gif) | ClearChildState | Deletes the view-state and control-state information for all the server control's child controls. (Inherited from Control.) | .gif) | ClearChildViewState | Deletes the view-state information for all the server control's child controls. (Inherited from Control.) | .gif) | ClearEffectiveClientIDMode | Infrastructure. Sets the ClientIDMode property of the current control instance and of any child controls to Inherit. (Inherited from Control.) | .gif) | CopyBaseAttributes | Copies the properties not encapsulated by the Style object from the specified Web server control to the Web server control that this method is called from. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | CreateChildControls | Creates the individual controls that make up the Login control and associates event handlers with their events. (Overrides Control..::.CreateChildControls()()().) | .gif) | CreateControlCollection | Creates a new ControlCollection object to hold the child controls (both literal and server) of the server control. (Inherited from Control.) | .gif) | CreateControlStyle | Creates the style object that is used internally by the WebControl class to implement all style related properties. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | DataBind()()() | Binds a data source to the CompositeControl and all its child controls. (Inherited from CompositeControl.) | .gif) | DataBind(Boolean) | Binds a data source to the invoked server control and all its child controls with an option to raise the DataBinding event. (Inherited from Control.) | .gif) | DataBindChildren | Binds a data source to the server control's child controls. (Inherited from Control.) | .gif) | Dispose | Enables a server control to perform final clean up before it is released from memory. (Inherited from Control.) | .gif) | EnsureChildControls | Determines whether the server control contains child controls. If it does not, it creates child controls. (Inherited from Control.) | .gif) | EnsureID | Creates an identifier for controls that do not have an identifier assigned. (Inherited from Control.) | .gif) | Equals(Object) | Determines whether the specified Object is equal to the current Object. (Inherited from Object.) | .gif) | Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) | .gif) | FindControl(String) | Searches the current naming container for a server control with the specified id parameter. (Inherited from Control.) | .gif) | FindControl(String, Int32) | Infrastructure. Searches the current naming container for a server control with the specified id and an integer, specified in the pathOffset parameter, which aids in the search. You should not override this version of the FindControl method. (Inherited from Control.) | .gif) | Focus | Sets input focus to a control. (Inherited from Control.) | .gif) | GetDesignModeState | Infrastructure. Gets design-time data for a control. (Inherited from Control.) | .gif) | GetHashCode | Serves as a hash function for a particular type. (Inherited from Object.) | .gif) | GetRouteUrl(Object) | Gets the URL that corresponds to a set of route parameters. (Inherited from Control.) | .gif) | GetRouteUrl(RouteValueDictionary) | Gets the URL that corresponds to a set of route parameters. (Inherited from Control.) | .gif) | GetRouteUrl(String, Object) | Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.) | .gif) | GetRouteUrl(String, RouteValueDictionary) | Gets the URL that corresponds to a set of route parameters and a route name. (Inherited from Control.) | .gif) | GetType | Gets the Type of the current instance. (Inherited from Object.) | .gif) | GetUniqueIDRelativeTo | Returns the prefixed portion of the UniqueID property of the specified control. (Inherited from Control.) | .gif) | HasControls | Determines if the server control contains any child controls. (Inherited from Control.) | .gif) | HasEvents | Returns a value indicating whether events are registered for the control or any child controls. (Inherited from Control.) | .gif) | IsLiteralContent | Infrastructure. Determines if the server control holds only literal content. (Inherited from Control.) | .gif) | LoadControlState | Restores control-state information from a previous page request that was saved by the SaveControlState method. (Inherited from Control.) | .gif) | LoadViewState | Infrastructure. Restores view-state information from a previous request that was saved with the SaveViewState method. (Overrides WebControl..::.LoadViewState(Object).) | .gif) | MapPathSecure | Retrieves the physical path that a virtual path, either absolute or relative, maps to. (Inherited from Control.) | .gif) | MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) | .gif) | MergeStyle | Copies any nonblank elements of the specified style to the Web control, but will not overwrite any existing style elements of the control. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | OnAuthenticate | Raises the Authenticate event to authenticate the user. | .gif) | OnBubbleEvent | Determines whether to pass an event up the page's user interface (UI) server control hierarchy. (Overrides Control..::.OnBubbleEvent(Object, EventArgs).) | .gif) | OnDataBinding | Raises the DataBinding event. (Inherited from Control.) | .gif) | OnInit | Raises the Init event. (Inherited from Control.) | .gif) | OnLoad | Raises the Load event. (Inherited from Control.) | .gif) | OnLoggedIn | Raises the LoggedIn event after the user logs in to the Web site and has been authenticated. | .gif) | OnLoggingIn | Raises the LoggingIn event when a user submits login information but before the authentication takes place. | .gif) | OnLoginError | Raises the LoginError event when a login attempt fails. | .gif) | OnPreRender | Implements the base Control..::.OnPreRender method. (Overrides Control..::.OnPreRender(EventArgs).) | .gif) | OnUnload | Raises the Unload event. (Inherited from Control.) | .gif) | OpenFile | Gets a Stream used to read a file. (Inherited from Control.) | .gif) | RaiseBubbleEvent | Assigns any sources of the event and its information to the control's parent. (Inherited from Control.) | .gif) | RecreateChildControls | Recreates the child controls in a control derived from CompositeControl. (Inherited from CompositeControl.) | .gif) | RemovedControl | Called after a child control is removed from the Controls collection of the Control object. (Inherited from Control.) | .gif) | Render | Infrastructure. Renders the login form using the specified HTML writer. (Overrides CompositeControl..::.Render(HtmlTextWriter).) | .gif) | RenderBeginTag | Renders the HTML opening tag of the control to the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | RenderChildren | Outputs the content of a server control's children to a provided HtmlTextWriter object, which writes the content to be rendered on the client. (Inherited from Control.) | .gif) | RenderContents | Renders the contents of the control to the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | RenderControl(HtmlTextWriter) | Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled. (Inherited from Control.) | .gif) | RenderControl(HtmlTextWriter, ControlAdapter) | Outputs server control content to a provided HtmlTextWriter object using a provided ControlAdapter object. (Inherited from Control.) | .gif) | RenderEndTag | Renders the HTML closing tag of the control into the specified writer. This method is used primarily by control developers. (Inherited from WebControl.) | .gif) | ResolveAdapter | Gets the control adapter responsible for rendering the specified control. (Inherited from Control.) | .gif) | ResolveClientUrl | Gets a URL that can be used by the browser. (Inherited from Control.) | .gif) | ResolveUrl | Converts a URL into one that is usable on the requesting client. (Inherited from Control.) | .gif) | SaveControlState | Saves any server control state changes that have occurred since the time the page was posted back to the server. (Inherited from Control.) | .gif) | SaveViewState | Infrastructure. Saves any state that was modified after the TrackViewState method was invoked. (Overrides WebControl..::.SaveViewState()()().) | .gif) | SetDesignModeState | Sets design-time data for a control. (Overrides Control..::.SetDesignModeState(IDictionary).) | .gif) | SetRenderMethodDelegate | Infrastructure. Assigns an event handler delegate to render the server control and its content into its parent control. (Inherited from Control.) | .gif) | ToString | Returns a string that represents the current object. (Inherited from Object.) | .gif) | TrackViewState | Overrides the base Control..::.TrackViewState method. (Overrides WebControl..::.TrackViewState()()().) | Top

Extension Methods

Fields

Explicit Interface Implementations
|
| Name | Description |
|---|
.gif) .gif) | IAttributeAccessor..::.GetAttribute | Infrastructure. Gets an attribute of the Web control with the specified name. (Inherited from WebControl.) | .gif) .gif) | IAttributeAccessor..::.SetAttribute | Sets an attribute of the Web control to the specified name and value. (Inherited from WebControl.) | .gif) .gif) | ICompositeControlDesignerAccessor..::.RecreateChildControls | Enables a designer to recreate the composite control's collection of child controls in the design-time environment. (Inherited from CompositeControl.) | .gif) .gif) | IControlBuilderAccessor..::.ControlBuilder | For a description of this member, see IControlBuilderAccessor..::.ControlBuilder. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.GetDesignModeState | For a description of this member, see IControlDesignerAccessor..::.GetDesignModeState. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetDesignModeState | For a description of this member, see IControlDesignerAccessor..::.SetDesignModeState. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetOwnerControl | Infrastructure. For a description of this member, see IControlDesignerAccessor..::.SetOwnerControl. (Inherited from Control.) | .gif) .gif) | IControlDesignerAccessor..::.UserData | For a description of this member, see IControlDesignerAccessor..::.UserData. (Inherited from Control.) | .gif) .gif) | IDataBindingsAccessor..::.DataBindings | For a description of this member, see IDataBindingsAccessor..::.DataBindings. (Inherited from Control.) | .gif) .gif) | IDataBindingsAccessor..::.HasDataBindings | For a description of this member, see IDataBindingsAccessor..::.HasDataBindings. (Inherited from Control.) | .gif) .gif) | IExpressionsAccessor..::.Expressions | For a description of this member, see IExpressionsAccessor..::.Expressions. (Inherited from Control.) | .gif) .gif) | IExpressionsAccessor..::.HasExpressions | For a description of this member, see IExpressionsAccessor..::.HasExpressions. (Inherited from Control.) | .gif) .gif) | IParserAccessor..::.AddParsedSubObject | For a description of this member, see IParserAccessor..::.AddParsedSubObject. (Inherited from Control.) | Top

Remarks
In this topic: IntroductionThe Login control is a composite control that provides all the common UI elements needed to authenticate a user on a Web site. The following three elements are required for all login scenarios: A unique user name to identify the user. A password to verify the identity of the user. A login button to send the login information to the server.
The Login control also provides the following optional UI elements that support additional functions: A link for a password reminder. A Remember Me checkbox for retaining the login information between sessions. A Help link for users who are having trouble logging in. A Register New User link that redirects users to a registration page. Instruction text that appears on the login form. Custom error text that appears when the user clicks the login button without filling in the user name or password fields. Custom error text that appears if the login fails. A custom action that occurs when login succeeds. A way to hide the login control if the user is already logged in to the site.
For a table showing which controls are required and which are optional, see LayoutTemplate property. Security Note |
|---|
Accepting user input is a potential security threat. Malicious users can send data that is intended to expose vulnerabilities or run programs that try generated passwords. To improve security when working with user input, you should use the validation features of your control and secure any data providers that are configured for your control. For more information, see Securing Login Controls, Basic Security Practices for Web Applications, and Securing Membership. |
The Login control uses a membership provider to obtain user credentials. Unless you specify otherwise, the Login control uses the default membership provider defined in the Web.config file. To specify a different provider, set the MembershipProvider property to one of the membership provider names defined in your application's Web.config file. For more information, see Membership Providers. If you want to use a custom authentication service, you can use the OnAuthenticate method to call the service. Styles and TemplatesThe appearance of the Login control is fully customizable through templates and style settings. All UI text messages are also customizable through properties of the Login class. The default interface text is automatically localized based on the locale setting on the server. If the Login control is customized with templates, then the AccessKey property and the TabIndex property are ignored. In this case, set the AccessKey property and the TabIndex property of each template child control directly.
Login control properties represented by text boxes, such as UserName and Password, are accessible during all phases of the page life cycle. The control will pick up any changes made by the end user by means of the TextChanged event triggered by the textboxes. Note |
|---|
If you embed the Login control in a WizardStep object, explicitly set the ActiveStepIndex property in a Page_Load event handler if the user is authenticated. The Wizard control does not automatically advance to the next WizardStep object in this scenario. |
The following table lists the Login control style properties and explains which UI element each style property affects. For a list of which properties each style applies to, see the documentation for the individual style properties. Validation GroupingsThe UserName and Password properties have RequiredFieldValidator controls associated with them to prevent users from submitting the page without providing required information. The Login control uses a validation group so that other fields on the same page as the Login control can be validated separately. By default, the ID property of the Login control is used as the name of the validation group. For example, a Login control with the ID "Login1" will use a validation group name of "Login1". If you want to set the validation group that the Login control is part of, you must template the control and change the validation group name. Applying CSS StylesThe Login control lets you specify CSS style rules in markup. If you use templates to customize the appearance of the Login control, you can specify CSS styles in the markup in the templates. In that case, no extra outer table is required. You can prevent the table from being rendered by setting the RenderOuterTable property to false. AccessibilityDeclarative Syntax
<asp:Login
AccessKey="string"
BackColor="color name|#dddddd"
BorderColor="color name|#dddddd"
BorderPadding="integer"
BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
Inset|Outset"
BorderWidth="size"
CreateUserIconUrl="uri"
CreateUserText="string"
CreateUserUrl="uri"
CssClass="string"
DestinationPageUrl="uri"
DisplayRememberMe="True|False"
Enabled="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
FailureAction="Refresh|RedirectToLoginPage"
FailureText="string"
Font-Bold="True|False"
Font-Italic="True|False"
Font-Names="string"
Font-Overline="True|False"
Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|
Large|X-Large|XX-Large"
Font-Strikeout="True|False"
Font-Underline="True|False"
ForeColor="color name|#dddddd"
Height="size"
HelpPageIconUrl="uri"
HelpPageText="string"
HelpPageUrl="uri"
ID="string"
InstructionText="string"
LoginButtonImageUrl="uri"
LoginButtonText="string"
LoginButtonType="Button|Image|Link"
MembershipProvider="string"
OnAuthenticate="Authenticate event handler"
OnDataBinding="DataBinding event handler"
OnDisposed="Disposed event handler"
OnInit="Init event handler"
OnLoad="Load event handler"
OnLoggedIn="LoggedIn event handler"
OnLoggingIn="LoggingIn event handler"
OnLoginError="LoginError event handler"
OnPreRender="PreRender event handler"
OnUnload="Unload event handler"
Orientation="Horizontal|Vertical"
PasswordLabelText="string"
PasswordRecoveryIconUrl="uri"
PasswordRecoveryText="string"
PasswordRecoveryUrl="uri"
PasswordRequiredErrorMessage="string"
RememberMeSet="True|False"
RememberMeText="string"
runat="server"
SkinID="string"
Style="string"
TabIndex="integer"
TextLayout="TextOnLeft|TextOnTop"
TitleText="string"
ToolTip="string"
UserName="string"
UserNameLabelText="string"
UserNameRequiredErrorMessage="string"
Visible="True|False"
VisibleWhenLoggedIn="True|False"
Width="size"
>
<CheckBoxStyle />
<FailureTextStyle />
<HyperLinkStyle />
<InstructionTextStyle />
<LabelStyle />
<LayoutTemplate>
<!-- child controls -->
</LayoutTemplate>
<LoginButtonStyle />
<TextBoxStyle />
<TitleTextStyle />
<ValidatorTextStyle />
</asp:Login>

Examples
The following code example uses a Login control to provide a UI for logging in to a Web site.
<%@ Page Language="VB" %>
<%@ Import Namespace="System.ComponentModel" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Function IsValidEmail(ByVal strIn As String) As Boolean
' Return true if strIn is in valid e-mail format.
Return Regex.IsMatch(strIn, ("^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"))
End Function
Sub OnLoggingIn(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LoginCancelEventArgs)
If Not IsValidEmail(Login1.UserName) Then
Login1.InstructionText = "Enter a valid e-mail address."
Login1.InstructionTextStyle.ForeColor = System.Drawing.Color.RosyBrown
e.Cancel = True
Else
Login1.InstructionText = String.Empty
End If
End Sub
Sub OnLoginError(ByVal sender As Object, ByVal e As EventArgs)
Login1.HelpPageText = "Help with logging in..."
Login1.PasswordRecoveryText = "Forgot your password?"
End Sub
</script>
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Login id="Login1" runat="server"
BorderStyle="Solid"
BackColor="#F7F7DE"
BorderWidth="1px"
BorderColor="#CCCC99"
Font-Size="10pt"
Font-Names="Verdana"
CreateUserText="Create a new user..."
CreateUserUrl="newUser.aspx"
HelpPageUrl="help.aspx"
PasswordRecoveryUrl="getPass.aspx"
UserNameLabelText="E-mail address:"
OnLoggingIn="OnLoggingIn"
OnLoginError="OnLoginError" >
<TitleTextStyle Font-Bold="True"
ForeColor="#FFFFFF"
BackColor="#6B696B">
</TitleTextStyle>
</asp:Login>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.ComponentModel" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
void OnLoggingIn(object sender, System.Web.UI.WebControls.LoginCancelEventArgs e)
{
if (!IsValidEmail(Login1.UserName))
{
Login1.InstructionText = "Enter a valid e-mail address.";
Login1.InstructionTextStyle.ForeColor = System.Drawing.Color.RosyBrown;
e.Cancel = true;
}
else
{
Login1.InstructionText = String.Empty;
}
}
void OnLoginError(object sender, EventArgs e)
{
Login1.HelpPageText = "Help with logging in...";
Login1.PasswordRecoveryText = "Forgot your password?";
}
</script>
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Login id="Login1" runat="server"
BorderStyle="Solid"
BackColor="#F7F7DE"
BorderWidth="1px"
BorderColor="#CCCC99"
Font-Size="10pt"
Font-Names="Verdana"
CreateUserText="Create a new user..."
CreateUserUrl="newUser.aspx"
HelpPageUrl="help.aspx"
PasswordRecoveryUrl="getPass.aspx"
UserNameLabelText="E-mail address:"
OnLoggingIn="OnLoggingIn"
OnLoginError="OnLoginError" >
<TitleTextStyle Font-Bold="True"
ForeColor="#FFFFFF"
BackColor="#6B696B">
</TitleTextStyle>
</asp:Login>
</form>
</body>
</html>
The following code example demonstrates how you can extend the Login control. The CustomLogin control includes a DropDownList control that lets users choose which membership provider they are authenticated with. (These providers are configured in Web.config.) In the OnLoggingIn method, the MembershipProvider property is set to the selected value of the DropDownList control. 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. |
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Namespace Samples.AspNet.Controls
NotInheritable Public Class CustomLogin
Inherits Login
Public Sub New()
End Sub 'New
Protected Overrides Sub OnLoggingIn(ByVal e As LoginCancelEventArgs)
' Set the Membership provider for the Login control from a DropDownList.
Dim list As DropDownList = CType(Me.FindControl("domain"), DropDownList)
Me.MembershipProvider = list.SelectedValue
MyBase.OnLoggingIn(e)
End Sub 'OnLoggingIn
Protected Overrides Sub CreateChildControls()
LayoutTemplate = New MyTemplate()
MyBase.CreateChildControls()
End Sub 'CreateChildControls
End Class 'CustomLogin
' A Template that contains the child controls.
Public Class MyTemplate
Implements ITemplate
Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn
' A TextBox for the user name.
Dim username As New TextBox()
username.ID = "username"
' A TextBox for the password.
Dim password As New TextBox()
password.ID = "password"
' A CheckBox to remember the user on subsequent visits.
Dim remember As New CheckBox()
remember.ID = "RememberMe"
remember.Text = "Don't forget me!"
' Failure Text.
Dim failure As New Literal()
failure.ID = "FailureText"
' A DropDownList to choose the Membership provider.
Dim domain As New DropDownList()
domain.ID = "Domain"
domain.Items.Add(New ListItem("SqlMembers"))
domain.Items.Add(New ListItem("SqlMembers2"))
' A Button to log in.
Dim submit As New Button()
submit.CommandName = "login"
submit.Text = "LOGIN"
container.Controls.Add(New LiteralControl("UserName:"))
container.Controls.Add(username)
container.Controls.Add(New LiteralControl("<br>Password:"))
container.Controls.Add(password)
container.Controls.Add(New LiteralControl("<br>"))
container.Controls.Add(remember)
container.Controls.Add(New LiteralControl("<br>Domain:"))
container.Controls.Add(domain)
container.Controls.Add(New LiteralControl("<br>"))
container.Controls.Add(failure)
container.Controls.Add(New LiteralControl("<br>"))
container.Controls.Add(submit)
End Sub 'ITemplate.InstantiateIn
End Class 'MyTemplate
End Namespace
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace Samples.AspNet.Controls
{
public sealed class CustomLogin : Login
{
public CustomLogin() { }
protected override void OnLoggingIn(LoginCancelEventArgs e)
{
// Set the Membership provider for the Login control from a DropDownList.
DropDownList list = (DropDownList)this.FindControl("domain");
this.MembershipProvider = list.SelectedValue;
base.OnLoggingIn(e);
}
protected override void CreateChildControls()
{
LayoutTemplate = new MyTemplate();
base.CreateChildControls();
}
}
// A Template that contains the child controls.
public class MyTemplate : ITemplate
{
void ITemplate.InstantiateIn(Control container)
{
// A TextBox for the user name.
TextBox username = new TextBox();
username.ID = "username";
// A TextBox for the password.
TextBox password = new TextBox();
password.ID = "password";
// A CheckBox to remember the user on subsequent visits.
CheckBox remember = new CheckBox();
remember.ID = "RememberMe";
remember.Text = "Don't forget me!";
// Failure Text.
Literal failure = new Literal();
failure.ID = "FailureText";
// A DropDownList to choose the Membership provider.
DropDownList domain = new DropDownList();
domain.ID = "Domain";
domain.Items.Add(new ListItem("SqlMembers"));
domain.Items.Add(new ListItem("SqlMembers2"));
// A Button to log in.
Button submit = new Button();
submit.CommandName = "login";
submit.Text = "LOGIN";
container.Controls.Add(new LiteralControl("UserName:"));
container.Controls.Add(username);
container.Controls.Add(new LiteralControl("<br>Password:"));
container.Controls.Add(password);
container.Controls.Add(new LiteralControl("<br>"));
container.Controls.Add(remember);
container.Controls.Add(new LiteralControl("<br>Domain:"));
container.Controls.Add(domain);
container.Controls.Add(new LiteralControl("<br>"));
container.Controls.Add(failure);
container.Controls.Add(new LiteralControl("<br>"));
container.Controls.Add(submit);
}
}
}

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
|
Bibliothèque de classes .NET Framework Login, classe Fournit des éléments d'interface utilisateur permettant de se connecter à un site Web.

Hiérarchie d'héritage
Espace de noms :
System.Web.UI.WebControls
Assembly :
System.Web (dans System.Web.dll)

Syntaxe
<BindableAttribute(False)> _
Public Class Login _
Inherits CompositeControl
[BindableAttribute(false)]
public class Login : CompositeControl
[BindableAttribute(false)]
public ref class Login : public CompositeControl
[<BindableAttribute(false)>]
type Login =
class
inherit CompositeControl
end
Le type Login expose les membres suivants.

Constructeurs
|
| Nom | Description |
|---|
.gif) | Login | Crée une instance du contrôle Login. | Début

Méthodes
|
| Nom | Description |
|---|
.gif) | AddAttributesToRender | Ajoute des attributs et des styles HTML qui doivent être rendus au HtmlTextWriterTag spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | AddedControl | Appelée après l'ajout d'un contrôle enfant à la collection Controls de l'objet Control. (Hérité de Control.) | .gif) | AddParsedSubObject | Avertit le contrôle serveur qu'un élément XML ou HTML a été analysé et l'ajoute à l'objet ControlCollection du contrôle serveur. (Hérité de Control.) | .gif) | ApplyStyle | Copie tous les éléments non vides du style spécifié vers le contrôle Web, en remplaçant les éléments de style existants du contrôle. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | ApplyStyleSheetSkin | Applique les propriétés de style définies dans la feuille de style de la page au contrôle. (Hérité de Control.) | .gif) | BuildProfileTree | Infrastructure. Collecte des informations sur le contrôle serveur et les livre à la propriété Trace à afficher lorsque le traçage est activé pour la page. (Hérité de Control.) | .gif) | ClearCachedClientID | Infrastructure. Affecte à la valeur ClientID mise en cache la valeur nullNothingnullptrune référence null (Nothing en Visual Basic). (Hérité de Control.) | .gif) | ClearChildControlState | Supprime les informations sur l'état du contrôle des contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearChildState | Supprime les informations sur l'état d'affichage et sur l'état du contrôle de tous les contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearChildViewState | Supprime les informations d'état d'affichage de tous les contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | ClearEffectiveClientIDMode | Infrastructure. Affecte la valeur Inherit à la propriété ClientIDMode de l'instance de contrôle actuelle et de tous contrôles enfants. (Hérité de Control.) | .gif) | CopyBaseAttributes | Copie les propriétés non encapsulées par l'objet Style du contrôle serveur Web spécifié vers le contrôle serveur Web à partir duquel cette méthode est appelée. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | CreateChildControls | Crée les contrôles qui forment le contrôle Login et associent des gestionnaires d'événements à leurs événements. (Substitue Control..::.CreateChildControls()()().) | .gif) | CreateControlCollection | Crée un nouvel objet ControlCollection pour contenir les contrôles enfants (littéraux et serveur) du contrôle serveur. (Hérité de Control.) | .gif) | CreateControlStyle | Crée l'objet de style qui est utilisé de manière interne par la classe WebControl pour implémenter toutes les propriétés associées au style. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | DataBind()()() | Lie une source de données au CompositeControl et à tous ses contrôles enfants. (Hérité de CompositeControl.) | .gif) | DataBind(Boolean) | Lie une source de données au contrôle serveur appelé et tous ses contrôles enfants avec une option pour déclencher l'événement DataBinding. (Hérité de Control.) | .gif) | DataBindChildren | Lie une source de données aux contrôles enfants du contrôle serveur. (Hérité de Control.) | .gif) | Dispose | Permet à un contrôle serveur d'effectuer le nettoyage final avant qu'il soit libéré de la mémoire. (Hérité de Control.) | .gif) | EnsureChildControls | Détermine si le contrôle serveur contient des contrôles enfants. S'il ne contient pas de contrôles enfants, il en crée. (Hérité de Control.) | .gif) | EnsureID | Crée un identificateur pour les contrôles auxquels aucun identificateur n'est assigné. (Hérité de Control.) | .gif) | Equals(Object) | Détermine si l'Object spécifié est égal à l'Object en cours. (Hérité de Object.) | .gif) | Finalize | Autorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de netto***ge avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.) | .gif) | FindControl(String) | Recherche un contrôle serveur possédant le paramètre id spécifié dans le conteneur d'attribution de noms actuel. (Hérité de Control.) | .gif) | FindControl(String, Int32) | Infrastructure. Recherche le conteneur d'attribution de noms actuel d'un contrôle serveur avec l'id spécifié et un entier, spécifié dans le paramètre pathOffset, qui facilite la recherche. Vous ne devez pas substituer cette version de la méthode FindControl. (Hérité de Control.) | .gif) | Focus | Affecte le focus d'entrée à un contrôle. (Hérité de Control.) | .gif) | GetDesignModeState | Infrastructure. Obtient les données au moment du design pour un contrôle. (Hérité de Control.) | .gif) | GetHashCode | Sert de fonction de hachage pour un type particulier. (Hérité de Object.) | .gif) | GetRouteUrl(Object) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(RouteValueDictionary) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(String, Object) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire et à un nom d'itinéraire. (Hérité de Control.) | .gif) | GetRouteUrl(String, RouteValueDictionary) | Obtient l'URL qui correspond à un jeu de paramètres d'itinéraire et à un nom d'itinéraire. (Hérité de Control.) | .gif) | GetType | Obtient le Type de l'instance actuelle. (Hérité de Object.) | .gif) | GetUniqueIDRelativeTo | Retourne la partie préfixée de la propriété UniqueID du contrôle spécifié. (Hérité de Control.) | .gif) | HasControls | Détermine si le contrôle serveur contient des contrôles enfants. (Hérité de Control.) | .gif) | HasEvents | Retourne une valeur indiquant si des événements sont inscrits pour le contrôle ou des contrôles enfants. (Hérité de Control.) | .gif) | IsLiteralContent | Infrastructure. Détermine si le contrôle serveur ne détient qu'un contenu littéral. (Hérité de Control.) | .gif) | LoadControlState | Restaure des informations sur l'état du contrôle à partir d'une demande de page antérieure enregistrée par la méthode SaveControlState. (Hérité de Control.) | .gif) | LoadViewState | Infrastructure. Restaure les informations d'état d'affichage à partir d'une précédente requête enregistrées avec la méthode SaveViewState. (Substitue WebControl..::.LoadViewState(Object).) | .gif) | MapPathSecure | Récupère le chemin d'accès physique auquel un chemin d'accès virtuel, absolu ou relatif, correspond. (Hérité de Control.) | .gif) | MemberwiseClone | Crée une copie superficielle de l'objet Object actif. (Hérité de Object.) | .gif) | MergeStyle | Copie tous les éléments non vides du style spécifié vers le contrôle Web, mais ne remplace aucun élément de style existant du contrôle. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | OnAuthenticate | Déclenche l'événement Authenticate pour authentifier l'utilisateur. | .gif) | OnBubbleEvent | Détermine s'il faut passer un événement en haut de la hiérarchie des contrôles serveur de l'interface utilisateur de la page. (Substitue Control..::.OnBubbleEvent(Object, EventArgs).) | .gif) | OnDataBinding | Déclenche l'événement DataBinding. (Hérité de Control.) | .gif) | OnInit | Déclenche l'événement Init. (Hérité de Control.) | .gif) | OnLoad | Déclenche l'événement Load. (Hérité de Control.) | .gif) | OnLoggedIn | Déclenche l'événement LoggedIn une fois que l'utilisateur s'est connecté au site Web et a été authentifié. | .gif) | OnLoggingIn | Déclenche l'événement LoggingIn lorsqu'un utilisateur envoie des informations de connexion mais avant que l'authentification ait lieu. | .gif) | OnLoginError | Déclenche l'événement LoginError lorsqu'une tentative de connexion échoue. | .gif) | OnPreRender | Implémente la méthode Control..::.OnPreRender de base. (Substitue Control..::.OnPreRender(EventArgs).) | .gif) | OnUnload | Déclenche l'événement Unload. (Hérité de Control.) | .gif) | OpenFile | Obtient un Stream utilisé pour lire un fichier. (Hérité de Control.) | .gif) | RaiseBubbleEvent | Assigne les sources éventuelles de l'événement et ses informations au parent du contrôle. (Hérité de Control.) | .gif) | RecreateChildControls | Recrée les contrôles enfants dans un contrôle dérivé de CompositeControl. (Hérité de CompositeControl.) | .gif) | RemovedControl | Appelée après la suppression d'un contrôle enfant dans la collection Controls de l'objet Control. (Hérité de Control.) | .gif) | Render | Infrastructure. Restitue le formulaire de connexion à l'aide de l'enregistreur HTML spécifié. (Substitue CompositeControl..::.Render(HtmlTextWriter).) | .gif) | RenderBeginTag | Génère le rendu de la balise d'ouverture HTML du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | RenderChildren | Renvoie le contenu des enfants d'un contrôle serveur dans un objet HtmlTextWriter fourni, qui écrit le contenu à rendre sur le client. (Hérité de Control.) | .gif) | RenderContents | Génère le rendu du contenu du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | RenderControl(HtmlTextWriter) | Renvoie le contenu du contrôle serveur dans un objet HtmlTextWriter fourni et stocke des informations de traçage au sujet du contrôle si le traçage est activé. (Hérité de Control.) | .gif) | RenderControl(HtmlTextWriter, ControlAdapter) | Génère le contenu du contrôle serveur dans un objet HtmlTextWriter à l'aide d'un objet ControlAdapter fourni. (Hérité de Control.) | .gif) | RenderEndTag | Génère le rendu de la balise de fermeture HTML du contrôle via le writer spécifié. Cette méthode est principalement utilisée par des développeurs de contrôles. (Hérité de WebControl.) | .gif) | ResolveAdapter | Obtient l'adaptateur de contrôles responsable du rendu du contrôle spécifié. (Hérité de Control.) | .gif) | ResolveClientUrl | Obtient une URL qui peut être utilisée par le navigateur. (Hérité de Control.) | .gif) | ResolveUrl | Convertit une URL en une URL que le client soit en mesure d'utiliser. (Hérité de Control.) | .gif) | SaveControlState | Enregistre les modifications éventuellement apportées à l'état du contrôle serveur depuis la publication de la page sur le serveur. (Hérité de Control.) | .gif) | SaveViewState | Infrastructure. Enregistre les états modifiés après l'appel de la méthode TrackViewState. (Substitue WebControl..::.SaveViewState()()().) | .gif) | SetDesignModeState | Définit les données au moment du design pour un contrôle. (Substitue Control..::.SetDesignModeState(IDictionary).) | .gif) | SetRenderMethodDelegate | Infrastructure. Assigne un délégué de gestionnaires d'événements pour générer le rendu du contrôle serveur et de son contenu dans son contrôle parent. (Hérité de Control.) | .gif) | ToString | Retourne une chaîne qui représente l'objet actuel. (Hérité de Object.) | .gif) | TrackViewState | Substitue la méthode Control..::.TrackViewState de base. (Substitue WebControl..::.TrackViewState()()().) | Début

Méthodes d'extension

Champs

Implémentations d'interface explicite
|
| Nom | Description |
|---|
.gif) .gif) | IAttributeAccessor..::.GetAttribute | Infrastructure. Obtient un attribut du contrôle Web avec le nom spécifié. (Hérité de WebControl.) | .gif) .gif) | IAttributeAccessor..::.SetAttribute | Affecte au nom et à la valeur spécifiés un attribut du contrôle Web. (Hérité de WebControl.) | .gif) .gif) | ICompositeControlDesignerAccessor..::.RecreateChildControls | Permet à un concepteur de recréer dans l'environnement au moment du design la collection du contrôle composite de contrôles enfants. (Hérité de CompositeControl.) | .gif) .gif) | IControlBuilderAccessor..::.ControlBuilder | Pour obtenir une description de ce membre, consultez IControlBuilderAccessor..::.ControlBuilder. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.GetDesignModeState | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.GetDesignModeState. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetDesignModeState | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.SetDesignModeState. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.SetOwnerControl | Infrastructure. Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.SetOwnerControl. (Hérité de Control.) | .gif) .gif) | IControlDesignerAccessor..::.UserData | Pour obtenir une description de ce membre, consultez IControlDesignerAccessor..::.UserData. (Hérité de Control.) | .gif) .gif) | IDataBindingsAccessor..::.DataBindings | Pour obtenir une description de ce membre, consultez IDataBindingsAccessor..::.DataBindings. (Hérité de Control.) | .gif) .gif) | IDataBindingsAccessor..::.HasDataBindings | Pour obtenir une description de ce membre, consultez IDataBindingsAccessor..::.HasDataBindings. (Hérité de Control.) | .gif) .gif) | IExpressionsAccessor..::.Expressions | Pour obtenir une description de ce membre, consultez IExpressionsAccessor..::.Expressions. (Hérité de Control.) | .gif) .gif) | IExpressionsAccessor..::.HasExpressions | Pour obtenir une description de ce membre, consultez IExpressionsAccessor..::.HasExpressions. (Hérité de Control.) | .gif) .gif) | IParserAccessor..::.AddParsedSubObject | Pour obtenir une description de ce membre, consultez IParserAccessor..::.AddParsedSubObject. (Hérité de Control.) | Début

Notes
Dans cette rubrique : IntroductionLe contrôle Login est un contrôle composite qui fournit tous les éléments communs de l''interface utilisateur nécessaire pour authentifier un utilisateur sur un site Web. Les trois éléments suivants sont requis pour tous les scénarios de connexion : Un nom d'utilisateur unique pour identifier l'utilisateur. Un mot de passe pour vérifier l'identité de l'utilisateur. Un bouton de connexion pour envoyer les informations de connexion au serveur.
Le contrôle Login fournit également les éléments facultatifs de l'interface utilisateur suivants qui prennent en charge des fonctions supplémentaires : Lien pour un rappel de mot de passe. Une case à cocher de mémorisation du mot de passe pour conserver les informations de connexion d'une session à l'autre. Un lien d'aide pour les utilisateurs qui ont des difficultés pour se connecter. Lien Inscrire un utilisateur qui redirige les utilisateurs vers une page d'inscription. Texte d'instruction qui apparaît sur le formulaire de connexion. Texte d'erreur personnalisé qui s'affiche lorsque l'utilisateur clique sur le bouton de connexion sans remplir les champs de nom d'utilisateur ou de mot de passe. Texte d'erreur personnalisé qui s'affiche si la connexion échoue. Action personnalisée qui se produit lorsque la connexion est réussie. Façon de masquer le contrôle de connexion si l'utilisateur est déjà connecté au site.
Pour obtenir un tableau affichant les contrôles requis et les contrôles facultatifs, consultez la propriété LayoutTemplate. Le contrôle Login utilise un fournisseur d'appartenances pour obtenir des informations d'identification utilisateur. Sauf indication contraire, le contrôle Login utilise le fournisseur d'appartenances par défaut défini dans le fichier Web.config. Pour spécifier un fournisseur différent, attribuez l'un des noms de fournisseurs d'appartenances définis dans le fichier Web.config de votre application à la propriété MembershipProvider. Pour plus d'informations, consultez Fournisseurs d'appartenances. Si vous souhaitez utiliser un service d'authentification personnalisé, vous pouvez utiliser la méthode OnAuthenticate pour appeler le service. Styles et modèlesL'apparence du contrôle Login est complètement personnalisable à l'aide des modèles et paramètres de style. Tous les messages texte d'interface utilisateur sont également personnalisables à l'aide des propriétés de la classe Login. Le texte d'interface par défaut est localisé automatiquement en fonction des paramètres régionaux du serveur. Si le contrôle Login est personnalisé avec les modèles, la propriété AccessKey et la propriété TabIndex sont ignorées. Dans ce cas, définissez directement la propriété AccessKey et la propriété TabIndex de chaque contrôle enfant de modèle.
Les propriétés du contrôle Login, représentées par des zones de texte telles que UserName et Password, sont accessibles pendant toutes les phases du cycle de vie de la page. Le contrôle reprendra toutes modifications apportées par l'utilisateur final au moyen de l'événement TextChanged déclenché par les zones de texte. Remarque |
|---|
Si vous incorporez le contrôle Login dans un objet WizardStep, définissez la propriété ActiveStepIndex de manière explicite dans un gestionnaire d'événements Page_Load si l'utilisateur est authentifié. Le contrôle Wizard n'avance pas automatiquement à l'objet WizardStep suivant de ce scénario. |
Le tableau suivant répertorie les propriétés de style du contrôle Login et décrit l'élément d'interface que chacune des propriétés de style affecte. Pour obtenir la liste des propriétés auxquelles chaque style s'applique, consultez la documentation des propriétés de style. Regroupements de validationLes propriétés UserName et Password ont des contrôles RequiredFieldValidator associés pour empêcher les utilisateurs d'envoyer la page sans fournir les informations requises. Le contrôle Login utilise un groupe de validation afin que d'autres champs situés sur la même page que le contrôle Login puissent être validés séparément. Par défaut, la propriété ID du contrôle Login est utilisée comme nom du groupe de validation. Par exemple, un contrôle Login dont l'ID est "Login1" utilise également "Login1" comme nom de groupe de validation. Si vous souhaitez définir le groupe de validation dont le contrôle Login fait partie, vous devez créer un modèle avec le contrôle et modifier le nom du groupe de validation. Application des styles CSSLe contrôle Login vous permet de spécifier des règles de style CSS dans la balise. Si vous utilisez des modèles pour personnaliser l'apparence du contrôle Login, vous pouvez spécifier des styles CSS dans le balisage que vous fournissez dans les modèles. Dans ce cas, aucune table externe supplémentaire n'est requise. Vous pouvez empêcher le rendu de la table en définissant la propriété RenderOuterTable à la valeur false. AccessibilitéSyntaxe déclarative
<asp:Login
AccessKey="string"
BackColor="color name|#dddddd"
BorderColor="color name|#dddddd"
BorderPadding="integer"
BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
Inset|Outset"
BorderWidth="size"
CreateUserIconUrl="uri"
CreateUserText="string"
CreateUserUrl="uri"
CssClass="string"
DestinationPageUrl="uri"
DisplayRememberMe="True|False"
Enabled="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
FailureAction="Refresh|RedirectToLoginPage"
FailureText="string"
Font-Bold="True|False"
Font-Italic="True|False"
Font-Names="string"
Font-Overline="True|False"
Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|
Large|X-Large|XX-Large"
Font-Strikeout="True|False"
Font-Underline="True|False"
ForeColor="color name|#dddddd"
Height="size"
HelpPageIconUrl="uri"
HelpPageText="string"
HelpPageUrl="uri"
ID="string"
InstructionText="string"
LoginButtonImageUrl="uri"
LoginButtonText="string"
LoginButtonType="Button|Image|Link"
MembershipProvider="string"
OnAuthenticate="Authenticate event handler"
OnDataBinding="DataBinding event handler"
OnDisposed="Disposed event handler"
OnInit="Init event handler"
OnLoad="Load event handler"
OnLoggedIn="LoggedIn event handler"
OnLoggingIn="LoggingIn event handler"
OnLoginError="LoginError event handler"
OnPreRender="PreRender event handler"
OnUnload="Unload event handler"
Orientation="Horizontal|Vertical"
PasswordLabelText="string"
PasswordRecoveryIconUrl="uri"
PasswordRecoveryText="string"
PasswordRecoveryUrl="uri"
PasswordRequiredErrorMessage="string"
RememberMeSet="True|False"
RememberMeText="string"
runat="server"
SkinID="string"
Style="string"
TabIndex="integer"
TextLayout="TextOnLeft|TextOnTop"
TitleText="string"
ToolTip="string"
UserName="string"
UserNameLabelText="string"
UserNameRequiredErrorMessage="string"
Visible="True|False"
VisibleWhenLoggedIn="True|False"
Width="size"
>
<CheckBoxStyle />
<FailureTextStyle />
<HyperLinkStyle />
<InstructionTextStyle />
<LabelStyle />
<LayoutTemplate>
<!-- child controls -->
</LayoutTemplate>
<LoginButtonStyle />
<TextBoxStyle />
<TitleTextStyle />
<ValidatorTextStyle />
</asp:Login>

Exemples
L'exemple de code suivant utilise un contrôle Login pour fournir une interface utilisateur pour se connecter à un site Web.
<%@ Page Language="VB" %>
<%@ Import Namespace="System.ComponentModel" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Function IsValidEmail(ByVal strIn As String) As Boolean
' Return true if strIn is in valid e-mail format.
Return Regex.IsMatch(strIn, ("^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"))
End Function
Sub OnLoggingIn(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LoginCancelEventArgs)
If Not IsValidEmail(Login1.UserName) Then
Login1.InstructionText = "Enter a valid e-mail address."
Login1.InstructionTextStyle.ForeColor = System.Drawing.Color.RosyBrown
e.Cancel = True
Else
Login1.InstructionText = String.Empty
End If
End Sub
Sub OnLoginError(ByVal sender As Object, ByVal e As EventArgs)
Login1.HelpPageText = "Help with logging in..."
Login1.PasswordRecoveryText = "Forgot your password?"
End Sub
</script>
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Login id="Login1" runat="server"
BorderStyle="Solid"
BackColor="#F7F7DE"
BorderWidth="1px"
BorderColor="#CCCC99"
Font-Size="10pt"
Font-Names="Verdana"
CreateUserText="Create a new user..."
CreateUserUrl="newUser.aspx"
HelpPageUrl="help.aspx"
PasswordRecoveryUrl="getPass.aspx"
UserNameLabelText="E-mail address:"
OnLoggingIn="OnLoggingIn"
OnLoginError="OnLoginError" >
<TitleTextStyle Font-Bold="True"
ForeColor="#FFFFFF"
BackColor="#6B696B">
</TitleTextStyle>
</asp:Login>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.ComponentModel" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
void OnLoggingIn(object sender, System.Web.UI.WebControls.LoginCancelEventArgs e)
{
if (!IsValidEmail(Login1.UserName))
{
Login1.InstructionText = "Enter a valid e-mail address.";
Login1.InstructionTextStyle.ForeColor = System.Drawing.Color.RosyBrown;
e.Cancel = true;
}
else
{
Login1.InstructionText = String.Empty;
}
}
void OnLoginError(object sender, EventArgs e)
{
Login1.HelpPageText = "Help with logging in...";
Login1.PasswordRecoveryText = "Forgot your password?";
}
</script>
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Login id="Login1" runat="server"
BorderStyle="Solid"
BackColor="#F7F7DE"
BorderWidth="1px"
BorderColor="#CCCC99"
Font-Size="10pt"
Font-Names="Verdana"
CreateUserText="Create a new user..."
CreateUserUrl="newUser.aspx"
HelpPageUrl="help.aspx"
PasswordRecoveryUrl="getPass.aspx"
UserNameLabelText="E-mail address:"
OnLoggingIn="OnLoggingIn"
OnLoginError="OnLoginError" >
<TitleTextStyle Font-Bold="True"
ForeColor="#FFFFFF"
BackColor="#6B696B">
</TitleTextStyle>
</asp:Login>
</form>
</body>
</html>
L'exemple de code suivant illustre comment étendre le contrôle Login. Le contrôle CustomLogin inclut un contrôle DropDownList qui permet aux utilisateurs de choisir avec quel fournisseur d'appartenances ils sont authentifiés. (Ces fournisseurs sont configurés dans Web.config.) Dans la méthode OnLoggingIn, la propriété MembershipProvider a la valeur sélectionnée du contrôle DropDownList. Note de sécurité |
|---|
Cet exemple comporte une zone de texte qui accepte l'entrée d'utilisateur, ce qui constitue une menace éventuelle pour la sécurité. Par défaut, les pages Web ASP.NET vérifient que l'entrée d'utilisateur n'inclut pas de script ni d'éléments HTML. Pour plus d'informations, consultez Vue d'ensemble des attaques de script. |
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Namespace Samples.AspNet.Controls
NotInheritable Public Class CustomLogin
Inherits Login
Public Sub New()
End Sub 'New
Protected Overrides Sub OnLoggingIn(ByVal e As LoginCancelEventArgs)
' Set the Membership provider for the Login control from a DropDownList.
Dim list As DropDownList = CType(Me.FindControl("domain"), DropDownList)
Me.MembershipProvider = list.SelectedValue
MyBase.OnLoggingIn(e)
End Sub 'OnLoggingIn
Protected Overrides Sub CreateChildControls()
LayoutTemplate = New MyTemplate()
MyBase.CreateChildControls()
End Sub 'CreateChildControls
End Class 'CustomLogin
' A Template that contains the child controls.
Public Class MyTemplate
Implements ITemplate
Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn
' A TextBox for the user name.
Dim username As New TextBox()
username.ID = "username"
' A TextBox for the password.
Dim password As New TextBox()
password.ID = "password"
' A CheckBox to remember the user on subsequent visits.
Dim remember As New CheckBox()
remember.ID = "RememberMe"
remember.Text = "Don't forget me!"
' Failure Text.
Dim failure As New Literal()
failure.ID = "FailureText"
' A DropDownList to choose the Membership provider.
Dim domain As New DropDownList()
domain.ID = "Domain"
domain.Items.Add(New ListItem("SqlMembers"))
domain.Items.Add(New ListItem("SqlMembers2"))
' A Button to log in.
Dim submit As New Button()
submit.CommandName = "login"
submit.Text = "LOGIN"
container.Controls.Add(New LiteralControl("UserName:"))
container.Controls.Add(username)
container.Controls.Add(New LiteralControl("<br>Password:"))
container.Controls.Add(password)
container.Controls.Add(New LiteralControl("<br>"))
container.Controls.Add(remember)
container.Controls.Add(New LiteralControl("<br>Domain:"))
container.Controls.Add(domain)
container.Controls.Add(New LiteralControl("<br>"))
container.Controls.Add(failure)
container.Controls.Add(New LiteralControl("<br>"))
container.Controls.Add(submit)
End Sub 'ITemplate.InstantiateIn
End Class 'MyTemplate
End Namespace
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace Samples.AspNet.Controls
{
public sealed class CustomLogin : Login
{
public CustomLogin() { }
protected override void OnLoggingIn(LoginCancelEventArgs e)
{
// Set the Membership provider for the Login control from a DropDownList.
DropDownList list = (DropDownList)this.FindControl("domain");
this.MembershipProvider = list.SelectedValue;
base.OnLoggingIn(e);
}
protected override void CreateChildControls()
{
LayoutTemplate = new MyTemplate();
base.CreateChildControls();
}
}
// A Template that contains the child controls.
public class MyTemplate : ITemplate
{
void ITemplate.InstantiateIn(Control container)
{
// A TextBox for the user name.
TextBox username = new TextBox();
username.ID = "username";
// A TextBox for the password.
TextBox password = new TextBox();
password.ID = "password";
// A CheckBox to remember the user on subsequent visits.
CheckBox remember = new CheckBox();
remember.ID = "RememberMe";
remember.Text = "Don't forget me!";
// Failure Text.
Literal failure = new Literal();
failure.ID = "FailureText";
// A DropDownList to choose the Membership provider.
DropDownList domain = new DropDownList();
domain.ID = "Domain";
domain.Items.Add(new ListItem("SqlMembers"));
domain.Items.Add(new ListItem("SqlMembers2"));
// A Button to log in.
Button submit = new Button();
submit.CommandName = "login";
submit.Text = "LOGIN";
container.Controls.Add(new LiteralControl("UserName:"));
container.Controls.Add(username);
container.Controls.Add(new LiteralControl("<br>Password:"));
container.Controls.Add(password);
container.Controls.Add(new LiteralControl("<br>"));
container.Controls.Add(remember);
container.Controls.Add(new LiteralControl("<br>Domain:"));
container.Controls.Add(domain);
container.Controls.Add(new LiteralControl("<br>"));
container.Controls.Add(failure);
container.Controls.Add(new LiteralControl("<br>"));
container.Controls.Add(submit);
}
}
}

Informations de version
.NET FrameworkPris en charge dans : 4, 3.5, 3.0, 2.0

Plateformes
Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2
Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.

Sécurité des threads
Tous les membres static ( Shared en Visual Basic) publics de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.

Voir aussi
RéférenceAutres ressources
|