Hi i've got a simple username and password entry on my webpage.

My login class works perfectly in Windows Form but not in my Web Application

Login class:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace assignmentForm
{
    public class UserLogin
    {
        private SqlConnection connection = new SqlConnection();

        public UserLogin()
        {
            ///create sql connection

            connection.ConnectionString = @"Data Source=localhost\sqlexpress;Initial Catalog=coffee;Integrated Security=True;Pooling=False";
            connection.Open();
        }

        public Boolean Login(String username, String password)
        {
            SqlCommand cmd = new SqlCommand("SELECT * FROM [users]  WHERE [username]='" + username + "' AND [password]='" + password + "'", connection);

            SqlDataReader reader = cmd.ExecuteReader();

            bool found = false;
            if (reader.Read())
            {
                found = true;
            }
            reader.Close();
            connection.Close();
            return found;
        }


    }

}

ASP.net

namespace AsgWeb
{

    public partial class login : System.Web.UI.Page
    {

        private UserLogin UserID;
                
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            UserID = new UserLogin();

            if (UserID.Login(txtUsername.Text, txtPassword.Text))
            {
               
                Response.Redirect("coffeeLogin.aspx");

            }
            else
            {
              
            }
            }
        }
    }
}

UserID = new UserLogin(); gives me an error saying it could not be found.

Dani AI

Generated

The error you saw when doing UserID = new UserLogin(); was almost certainly a visibility/namespace issue, not a runtime Web Forms bug. fixed it by putting the class where the page could see it. In a Web Application put your helper class in the same project and namespace (or add using YourNamespace;). In a Web Site project place it in App_Code or use the fully qualified name. Avoid opening a shared connection in a constructor — Web apps need short-lived connections.

To keep a user logged in across pages you can set a small server-side flag (user id or name) and check it on each page. Example (login handler):

Session["Username"] = username;
Response.Redirect("Default.aspx");

Then on Default.aspx (Page_Load):

if (Session["Username"] == null)
    Response.Redirect("Login.aspx");

Better options: use Forms Authentication (so Request.IsAuthenticated works) or centralize the check in a base page or Global.asax to avoid repeating code.

Security and reliability notes (important):

  • Never build SQL with string concatenation — that allows SQL injection. Use parameterized queries and using blocks so connections are closed immediately.
    using(var cn = new SqlConnection(connStr))
    using(var cmd = new SqlCommand("SELECT PasswordHash, Salt FROM Users WHERE Username = @u", cn))
    {
      cmd.Parameters.AddWithValue("@u", username);
      cn.Open();
      ...
    }
  • Do not store plain-text passwords. Store a salted hash (PBKDF2/Rfc2898DeriveBytes or an established library), and verify by deriving the hash for the entered password and comparing bytes.
  • Store connection strings in Web.config (ConfigurationManager) and avoid hard-coding credentials.

For maintainability: centralize auth checks (base page or HTTP module) and avoid storing sensitive data in Session. These steps will make the login reliable and much safer for a production site — something will appreciate as the app grows.

Recommended Answers

All 6 Replies

Please look this code after the modification,
login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click"/>
    </div>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

  
public partial class login : System.Web.UI.Page    
{         
    private UserLogin UserID;         
    protected void Page_Load(object sender, EventArgs e)        
    {         
        
    }         
    protected void Button1_Click(object sender, EventArgs e)        
    {      
        UserID = new UserLogin();
        if (UserID.Login(txtUsername.Text, txtPassword.Text))
        {
            Response.Redirect("alert message.aspx", false);
        }
        else
        { }            
    }        
}

UserLogin

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient; 
  
public class UserLogin    
{        
    private SqlConnection connection = new SqlConnection();         
    public UserLogin()        
    {            
        ///create sql connection             
//        connection.ConnectionString = @"Data Source=localhost\sqlexpress;Initial Catalog=coffee;Integrated Security=True;Pooling=False";            
        connection.ConnectionString = @"Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=****;Password=****;Pooling=False";            
        connection.Open();        
    }         
    public Boolean Login(String username, String password)        
    {
        SqlCommand cmd = new SqlCommand("SELECT * FROM [users]  WHERE [username]='" + username + "' AND [password]='" + password + "'", connection);             
        SqlDataReader reader = cmd.ExecuteReader();             
        bool found = false;            
        if (reader.Read())            
        {                
            found = true;            
        }            
        reader.Close();            
        connection.Close();            
        return found;        
    }      
}

Use ur data instead of ***

Thank you kindly that worked perfectly.

Is there anyway that I can check if the login was succesfull? Ie.

If Login is then redirec to here.aspx

else
redirect to login.aspx

What U written thats correct

if (UserID.Login(txtUsername.Text, txtPassword.Text))   //return true means login success else login failure    {            
Response.Redirect("alert message.aspx", false);        }        else        { }

Ok thank you that works for the login page.

What I wanted to do was to check they are logged in on the homepage.

Once user logs in they go to default.aspx.

I want that Default page to check IF user logged in - if yes then ok - if not redirect them to login.aspx

Is that possible?

Create a session or Viewstate variable to assign flag(Bool) value to identify, Is it the user is login in Home page or not, BAsed on session or Viewstate value u can redirect.

Thanks for your help :)

Its highly appreciated.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.