Friday, 23 December 2016

How to: Create an ASP.NET Login Page

How to: Create an ASP.NET Login Page


To create a login page

  1. Create an ASP.NET Web application that uses ASP.NET membership. For details and examples, see Configuring an ASP.NET Application to Use Membership.
  2. Create an ASP.NET Web page in your application named Login.aspx
  3. Add a Login control to the page.

First Create WebForm
<form id="form1" runat="server"><asp:Login ID = "Login1" runat = "server" OnAuthenticate= "ValidateUser"></asp:Login></form>

OnButton click event Copy and past this code

using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Security;

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;
        }
    }
}

So finaly your login form ready

0 comments:

Post a Comment