Login page using Entity Framework in ASP.Net using C# and VB.Net

Last Reply one month ago By dharmendr

Posted one month ago

How to create login page using asp.net and entity framework

Posted one month ago

Hi tex,

Using this article i have created the example. 

Using LoginName control in ASP.Net

Check this example. Now please take its reference and correct your code.

HTML

Login

<asp:Login ID="Login1" runat="server" OnAuthenticate="ValidateUser"></asp:Login>

Home

Welcome <asp:LoginName ID="LoginName1" runat="server" Font-Bold="true" />
<br /><br /><asp:LoginStatus ID="LoginStatus1" runat="server" />

Namespaces

C#

using System.Web.Security;

VB.Net

Imports System.Web.Security

Code

C#

Login

protected void ValidateUser(object sender, EventArgs e)
{
    LoginDBEntities entities = new LoginDBEntities();
    User user = entities.Users
                .Where(x => x.Username == Login1.UserName && x.Password == Login1.Password)
                .FirstOrDefault();
    if (user != null)
    {
        FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
    }
    else
    {
        Login1.FailureText = "Username and/or password is incorrect.";
    }
}

Home

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.Page.User.Identity.IsAuthenticated)
    {
        FormsAuthentication.RedirectToLoginPage();
    }
}

VB.Net

Login

Protected Sub ValidateUser(ByVal sender As Object, ByVal e As EventArgs)
    Dim entities As LoginDBEntities = New LoginDBEntities()
    Dim user As User = entities.Users _
                        .Where(Function(x) x.Username = Login1.UserName AndAlso x.Password = Login1.Password) _
                        .FirstOrDefault()

    If user IsNot Nothing Then
        FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
    Else
        Login1.FailureText = "Username and/or password is incorrect."
    End If
End Sub

Home

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

Screenshot

Note:

You can also use Stored Procedure to validate the login as in the above provided article.

For using Stored Procedure refer below article.

Entity Framework: Call Stored Procedure with Parameters using C# and VB.Net