且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET C#中的登录注销问题

更新时间:2023-02-25 16:54:16

尝试如下..
Try like below..
try
{
    conn.Open();
    SqlCommand cmd = new SqlCommand("select count(*) from tbl_mnadmin where mn_username='" +  txt_username.Text + "' and mn_password='" + txt_password.Text + "'", conn);
    int cnt=int.Parse(cmd.ExecuteScalar().ToString());

    if (cnt > 0)
    {
        Session["username"] = txt_username.Text;
        Session["pass"] = txt_password.Text;
        Response.Redirect("welcome.aspx");
     }
      else
        lbl_msg.Text = "Invalid User Name or Password";
}
catch (Exception ex)
{
}
finally
{
    conn.Close();
}


为自己的目的添加Tejas所说的话,不要那样做!
首先:
不要连接字符串以构建SQL命令.它使您对意外或蓄意的SQL注入攻击敞开大门,这可能会破坏整个数据库.请改用参数化查询.

例如,执行此操作的方式是,我不需要任何密码即可登录到您的系统-我要做的就是输入任何用户名,然后输入其他四个字符,然后我就可以登录了.或者,我可以进行扩展,登录(或不登录),然后从世界任何地方删除整个数据库.

其次:
切勿以明文形式存储密码!在这里看看:密码存储:操作方法. [ ^ ]
To add to what Tejas says, for your own sake, don''t do it like that!
Firstly:
Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

For example, the way you do it, I do not need any password to log into your system - all I have to do is enter any username, followed by four other characters, and I am logged in. Or, I could extend that, log in (or not log in), and delete your entire database, from anywhere in the world.

Secondly:
Never store passwords in clear text! Have a look here: Password Storage: How to do it.[^]


我认为您遇到了这个问题,因为您直接从sqlreader评估数据,而无需检查天气情况,即您的阅读器中是否有数据.因此,请修改您的代码以验证该部分,这样可能会解决您的问题.我想你可以尝试这样的事情...

I think you face this problem because you directly assessing your data from sqlreader with out checking weather there is data in your reader or not. so please modify your code to validate that part so, it might solve your problem. i think you can try something like this...

try
{
    conn.Open();
    SqlCommand cmd = new SqlCommand("select * from tbl_mnadmin where mn_username='" + txt_username.Text + "' and mn_password='" + txt_password.Text + "'", conn);
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read()) // put validation like this, it will go forward only if there is some data in your reader.
    {
        if (rdr["mn_username"].ToString().Length > 0)
        {
            Session["username"] = rdr["mn_username"];
            Session["pass"] = rdr["mn_password"];
            Response.Redirect("welcome.aspx");
        }
        else
        {
            lbl_msg.Text = "Invalid User Name or Password";
        }
    }
}
catch (Exception ex)
{
}
finally
{
    conn.Close();
}