简体   繁体   中英

Login page error in asp.net c#

I have a login page in which i have written code to login the admin part but it is not working i don't know what the problem is this the code is correct still getting unauthorized access. help me out

  string str = ConfigurationManager.ConnectionStrings["ottscon"].ConnectionString;
        using (SqlConnection con = new SqlConnection(str))
        {
            SqlCommand cmd = new SqlCommand("Select UserName,Password from login where UserName=@userid and Password=@passid", con);
            con.Open();
            cmd.Parameters.AddWithValue("@userid", TextBox1.ToString());
            cmd.Parameters.AddWithValue("@passid", TextBox2.ToString());
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds= new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count>0)
            {

               Session["login"] = TextBox1.Text;
               Response.Redirect("admintrator123/Default.aspx");
            }
            else
            {
                Label1.Text = "Unauthorized Access";
                Label1.ForeColor = System.Drawing.Color.Red;
            }
        }

You are not passing values properly

TextBox1.ToString() is wrong

use

TextBox1.Text

First use the value of the text inside the textbox (the existing ToString() is returning the type of the object TextBox ):

cmd.Parameters.AddWithValue("@userid", TextBox1.Text);
cmd.Parameters.AddWithValue("@passid", TextBox2.Text);

Try using this SQL to check if the record exist (inside the new SqlCommand() ):

SELECT CASE WHEN EXISTS (
    SELECT *
    FROM [login]
    WHERE UserName=@userid and Password=@passid
)
THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END

So you can then check on a bool and not on a row existance and have more understanding on what's happening.

After this you can read the value this way:

using (var reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        bool exist = reader.GetBoolean(0);
    }
}

try

logincommand = "Select UserName,Password from login where UserName='"+TextBox1.Text+"' and Password='"+TextBox2.Text+"'"
SqlCommand cmd = new SqlCommand(logincommand ,con);

and delete

        cmd.Parameters.AddWithValue("@userid", TextBox1.ToString());
        cmd.Parameters.AddWithValue("@passid", TextBox2.ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM