当前上下文中不存在变量C#

时间:2017-03-03 17:04:01

标签: c# asp.net

我正在asp.net中为登录页面编写一些服务器端验证。

现在,我来自一个"从头开始写#34; PHP的观点,我正在学习和努力解决一些我不知道的asp.net概念。

我正在尝试将用户名和密码变量设置为"有效"如果输入有效,我试图使用这些变量继续登录。

我也不确定这是否是正确的做事方式。

protected void loginbutton_Click(object sender, EventArgs e)
    {
        string UsernameRegex = "[a-zA-Z]+";
        string PasswordRegex = "[a-zA-Z0-9]+";

        if (!Regex.IsMatch(usernametextbox.Text, UsernameRegex))
        {
            string UsernameCheck = "valid";
        }
        else
        {
            string UsernameCheck = "invalid";
        }

        if (!Regex.IsMatch(passwordtextbox.Text, PasswordRegex))
        {
            string PasswordCheck = "valid";
        }
        else
        {
            string PasswordCheck = "invalid";
        }


        if(UsernameCheck = "valid") //i will include password here after i solved the problem
        {
            //do something
        }
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            conn.Open();
            string checkuser = "select count(*) from Users where Username = @username and Password = @password";

            SqlCommand com = new SqlCommand(checkuser, conn);
            com.Parameters.Add("@username", SqlDbType.NVarChar).Value = usernametextbox.Text;
            com.Parameters.Add("@password", SqlDbType.NVarChar).Value = passwordtextbox.Text;

            int temp = Convert.ToInt32(com.ExecuteScalar().ToString());

            if (temp > 0)
            {
                Response.Redirect("Cars.aspx");
            }
            else
            {
                loginfaillabel.Text = "Your Username or Password doesn't match our records";
            }
        }

感谢帮助和反馈。

4 个答案:

答案 0 :(得分:3)

好的,这里有很多反馈。

  1. 使用布尔语,而不是字符串!我替换了你。这里的主要问题是范围。您可以在if之外声明变量并解决问题,但最好使用布尔值,然后将它们全部放在一起,因为它变得更具可读性。
  2. 始终在IDisposable块中包装实现using的Ado.Net类型。这样,如果代码遇到异常,你的连接仍然关闭(一件好事)
  3. 无需在sql语句中执行count,只需返回1即可。如果有用户,则会得到结果,否则不会。
  4. 绝不以明文形式存储密码!我没碰到这个,这取决于你。有许多适当的密码哈希算法可供选择,例如pbkdf2bcryptscrypt,以列举一些更普遍接受的安全算法。
  5. 您确定用户名是Unicode吗?如果没有将参数类型更改为VarChar类型中的SqlParameter
  6. 修改后的代码

    protected void loginbutton_Click(object sender, EventArgs e)
    {
        string UsernameRegex = "[a-zA-Z]+";
        string PasswordRegex = "[a-zA-Z0-9]+";
    
        boolean isUsernameValid = Regex.IsMatch(usernametextbox.Text, UsernameRegex)
        boolean isPasswordValid = Regex.IsMatch(passwordtextbox.Text, PasswordRegex);
    
    
        if(!isUsernameValid || !isPasswordValid) //i will include password here after i solved the problem
        {
            //do something
        }
        else
        {
            const string checkuser = "SELECT 1 FROM Users WHERE Username = @username and Password = @password";
    
            using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
            using(SqlCommand com = new SqlCommand(checkuser, conn))
            {
                conn.Open();
    
                com.Parameters.Add("@username", SqlDbType.NVarChar).Value = usernametextbox.Text;
                com.Parameters.Add("@password", SqlDbType.NVarChar).Value = passwordtextbox.Text;
    
                object temp = com.ExecuteScalar();
    
                // I do not remember if it is null or System.DbNull.Value that is returned if nothing is returned
                // you will have to test it
                var didUserMatch = temp == null || temp == System.DbNull.Value ? false : true;
    
                if (didUserMatch)
                {
                    Response.Redirect("Cars.aspx");
                }
                else
                {
                    loginfaillabel.Text = "Your Username or Password doesn't match our records";
                }
            }
        }
    }
    

答案 1 :(得分:2)

我发现您的代码有3个问题:

  1. 你正在使用字符串变量*检查,你应该使用布尔值。

  2. if(UsernameCheck = "valid")行中,您实际上将值"valid"分配给UsernameCheck,如果您要测试相等性,请使用if(UsernameCheck == "valid")

  3. 您实际拥有的问题是由于变量范围。你在if / else语句中声明了变量UsernameCheckPasswordCheck,这意味着它们只存在于if / else中,当代码执行存在if / else时,变量不再存在,试试这段代码(请阅读更多关于C#的内容):

    protected void loginbutton_Click(object sender,EventArgs e)     {         string UsernameRegex =" [a-zA-Z] +&#34 ;;         string PasswordRegex =" [a-zA-Z0-9] +&#34 ;;

        bool UsernameCheck = false; // better name for this is isUsernameValie
    
        if (!Regex.IsMatch(usernametextbox.Text, UsernameRegex))
        {
            UsernameCheck = true;
        }
        else
        {
            UsernameCheck = false;
        }
    
        bool PasswordCheck = false;// better name for this is isPasswordValid
        if (!Regex.IsMatch(passwordtextbox.Text, PasswordRegex))
        {
             PasswordCheck = true;
        }
        else
        {
            PasswordCheck = false;
        }
    
    
        if (UsernameCheck == true) //i will include password here after i solved the problem
        {
            //do something
        }
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        conn.Open();
        string checkuser = "select count(*) from Users where Username = @username and Password = @password";
    
        SqlCommand com = new SqlCommand(checkuser, conn);
        com.Parameters.Add("@username", SqlDbType.NVarChar).Value = usernametextbox.Text;
        com.Parameters.Add("@password", SqlDbType.NVarChar).Value = passwordtextbox.Text;
    
        int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
    
        if (temp > 0)
        {
            Response.Redirect("Cars.aspx");
        }
        else
        {
            loginfaillabel.Text = "Your Username or Password doesn't match our records";
        }
    }
    

答案 2 :(得分:0)

you need check variable and method scops.

代码需要一点编辑

    protected void loginbutton_Click(object sender, EventArgs e)
    {
        string UsernameRegex = "[a-zA-Z]+";
        string PasswordRegex = "[a-zA-Z0-9]+";

        var userName = usernametextbox.Text;
        var password = passwordtextbox.Text;

        if (!Regex.IsMatch(userName, UsernameRegex))
        {
            // do something
            return; // There is no need to go on
        }

        if(!Regex.IsMatch(password, PasswordRegex))
        {
            // do something
            return; // There is no need to go on
        }

        //If we can come here, we can go DB

        // To be dispose when the job is done
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
        {

            try
            {
                // To be dispose when the job is done
                using (SqlCommand com = new SqlCommand(checkuser, conn))
                {
                    conn.Open();
                    string checkuser = "select count(*) from Users where Username = @username and Password = @password";
                    com.Parameters.Add("@username", SqlDbType.NVarChar).Value = userName;
                    com.Parameters.Add("@password", SqlDbType.NVarChar).Value = password;
                    int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
                    if (temp > 0)
                    {
                        Response.Redirect("Cars.aspx");
                    }
                    else
                    {
                        loginfaillabel.Text = "Your Username or Password doesn't match our records";
                    }
                }
            }
            catch (Exception ex)
            {

                // you can handle error. maybe logs
            }
        }
    }

答案 3 :(得分:0)

虽然您可以根据其他答案做事,但恕我直言,首先利用内置的Web Forms Validation 。如果它不足,然后做其他事情。

琐碎的例子:

  • <p>Username (Alphabetic only, no spaces):<br /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Username is required"></asp:RequiredFieldValidator> <asp:RegularExpressionValidator ID="NameValidator" runat="server" ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Invalid - Alaphabetic only" ValidationExpression="[a-zA-Z]+" EnableClientScript="True"></asp:RegularExpressionValidator> </p> <p>Password (Alphanumeric only, no spaces):<br /> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" Display="Dynamic" ErrorMessage="Password is required"></asp:RequiredFieldValidator> <asp:RegularExpressionValidator ID="PwdValidator" runat="server" ControlToValidate="TextBox2" Display="Dynamic" ErrorMessage="Invalid -Alphanumeric Only" ValidationExpression="[\w]+" EnableClientScript="True"></asp:RegularExpressionValidator> </p> <p> <asp:Button ID="Button1" runat="server" OnClick="BtnSubmit" Text="Login" /> </p>

    EnableClientScript
    默认情况下,

    TrueFalse。您可以将其设置为foo.aspx.cs来测试或查看没有客户端验证的情况(请参阅服务器端验证)。

  • public partial class foo: Page { protected void Page_Load(object sender, EventArgs e) { } protected void BtnSubmit(object sender, EventArgs e) { if (Page.IsValid) { //Do what you need to do only if IsValid which is the server-side validation check } } } (又名&#34;代码背后&#34;)

    {{1}}