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

7nbnzgx9  于 2023-05-19  发布在  .NET
关注(0)|答案(4)|浏览(126)

我在www.example.com为登录页面编写一些服务器端验证asp.net。
现在,我从一个“从头开始写”PHP的Angular 来看,我正在学习和努力与一些这些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";
            }
        }

帮助和反馈是赞赏。

z9smfwbn

z9smfwbn1#

虽然你可以根据其他答案做一些事情,恕我直言,首先利用内置的Web Forms Validation *。如果它不够,那么就做点别的。
简单的例子:

  • foo.aspx
<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默认为True。您可以将其设置为False来测试或查看在没有客户端验证的情况下会发生什么(请参阅服务器端验证)。

  • 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
        }
    }
}
qmelpv7a

qmelpv7a2#

这里有很多反馈。
1.使用布尔值,而不是字符串!我替你换了。这里的主要问题是什么有范围。你可以在if之外声明变量来解决这个问题,但最好使用布尔值,然后去掉if块,因为它变得更可读。
1.始终将实现IDisposable的Ado.NET类型 Package 在using块中。这样,如果代码遇到Exception,连接仍然是关闭的(这是一件好事)
1.不需要在SQL语句中执行count,只需返回1即可。如果有一个用户,你会得到一个结果,否则不会。
1.切勿以明文形式存储密码!我没碰这个,这取决于你。有许多合适的密码散列算法可供选择,如pbkdf2bcryptscrypt,以命名一些更普遍接受的安全算法。
1.是否确定用户名是Unicode?如果没有,在SqlParameter的类型中将参数类型更改为VarChar
修改代码

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

cfh9epnr3#

我发现你的代码有三个问题:
1.你正在为你的变量使用字符串 * 检查,你应该使用布尔值。
1.在if(UsernameCheck = "valid")行中,实际上是将值"valid"赋给UsernameCheck,如果要测试相等性,请使用if(UsernameCheck == "valid")
1.你实际上遇到的问题是由于变量的作用域。你在if/else语句中声明了变量UsernameCheckPasswordCheck,这意味着它们只存在于if/else语句中,当代码执行存在if/else时,变量就不再存在了,试试下面的代码(请多读一点C#):

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

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

bzzcjhmw4#

你需要检查变量和方法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
            }
        }
    }

相关问题