In this article I will explain with an example, how to implement and use the LoginName control in ASP.Net using C# and VB.Net.
In this article, the login form has been implemented using ASP.Net Login control and Forms Authentication.
The LoginName control is used to display the Username of the Logged in User in ASP.Net.
Database
The following Table Users is used in this article.
Note: You can download the database table SQL by clicking the download link below.
Stored Procedure to Validate the User Credentials
The following stored procedure is used to validate the user credentials, this stored procedure first checks whether the username and password are correct else returns -1.
If the username and password are correct but the user has not been activated then the code returned is -2.
If the username and password are correct and the user account has been activated then UserId of the user is returned by the stored procedure.
CREATE PROCEDURE [dbo].[Validate_User]
@Username NVARCHAR(20),
@Password NVARCHAR(20)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @UserId INT, @LastLoginDate DATETIME
SELECT @UserId = UserId, @LastLoginDate = LastLoginDate
FROM Users WHERE Username = @Username AND [Password] = @Password
IF @UserId IS NOT NULL
BEGIN
IF NOT EXISTS(SELECT UserId FROM UserActivation WHERE UserId = @UserId)
BEGIN
UPDATE Users
SET LastLoginDate = GETDATE()
WHERE UserId = @UserId
SELECT @UserId [UserId] -- User Valid
END
ELSE
BEGIN
SELECT -2 -- User not activated.
END
END
ELSE
BEGIN
SELECT -1 -- User invalid.
END
END
Login Page
This is the login form which will do the following:-
1. Authenticate user by verifying Username and Password.
HTML Markup
The HTML Markup consists of an ASP.Net Login control.
The ASP.Net Login control has been assigned with an OnAuthenticate event handler.
<asp:Login ID="Login1" runat="server" OnAuthenticate="ValidateUser"></asp:Login>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Security;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Security
Validating the User Credentials
When Login button is clicked, following event handler is executed.
Inside this event handler, the Username and Password entered by the user is passed to the stored procedure and its status is captured and if the value is not -1 (Username or password incorrect) or -2 (Account not activated) then the user is redirected to the Home page using FormsAuthentication RedirectFromLoginPage method.
C#
protected void ValidateUser(object sender, EventArgs e)
{
int userId = 0;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", Login1.UserName);
cmd.Parameters.AddWithValue("@Password", Login1.Password);
cmd.Connection = con;
con.Open();
userId = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
switch (userId)
{
case -1:
Login1.FailureText = "Username and/or password is incorrect.";
break;
case -2:
Login1.FailureText = "Account has not been activated.";
break;
default:
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
break;
}
}
}
VB.Net
Protected Sub ValidateUser(sender As Object, e As EventArgs)
Dim userId As Integer = 0
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("Validate_User")
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Username", Login1.UserName)
cmd.Parameters.AddWithValue("@Password", Login1.Password)
cmd.Connection = con
con.Open()
userId = Convert.ToInt32(cmd.ExecuteScalar())
con.Close()
End Using
Select Case userId
Case -1
Login1.FailureText = "Username and/or password is incorrect."
Exit Select
Case -2
Login1.FailureText = "Account has not been activated."
Exit Select
Case Else
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
Exit Select
End Select
End Using
End Sub
Home Page
After successful login user will be redirected to this page.
Displaying Username
The HTML Markup consists of an ASP.Net LoginName control to display the name of the Logged In user.
Logout
LoginStatus control is used to allow user Logout.
<div>
Welcome
<asp:LoginName ID="LoginName1" runat="server" Font-Bold="true" />
<br /><br />
<asp:LoginStatus ID="LoginStatus1" runat="server" />
</div>
Namespaces
You will need to import the following namespace.
C#
using System.Web.Security;
VB.Net
Imports System.Web.Security
Verifying User credentials and displaying Username
Inside the Page Load event handler, first a check is performed whether the User is authenticated using the IsAuthenticated property.
If User is authenticated then, the Username will be displayed in LoginName control.
If the user is not authenticated, then he is redirected back to the Login page using FormsAuthentication RedirectToLoginPage method.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.Page.User.Identity.IsAuthenticated Then
FormsAuthentication.RedirectToLoginPage()
End If
End Sub
Web.Config Configuration
You will need to add the following configuration in the Web.Config file in the system.web section.
<authentication mode="Forms">
<forms defaultUrl="~/Home.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880"></forms>
</authentication>
Screenshot
Downloads