简体   繁体   中英

asp.net website SQL connection

i'm having problems getting my ASP.NET site to log me in using SQL, here is some code (Login.ASPX.CS);

        private bool ValidateCredentials(string userName, string password)
    {
        bool returnValue = false;

        if (this.IsAlphaNumeric(userName) && userName.Length <= 50 && password.Length <= 50)
        {
            SqlConnection conn = null;

            try
            {
                string sql = "select count(*) from dbo.Users where UserName = '@username' and password = '@password'";

                conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MembershipSiteConStr"].ConnectionString);
                SqlCommand cmd = new SqlCommand(sql, conn);

                SqlParameter user = new SqlParameter();
                user.ParameterName = "@username";
                user.Value = userName.Trim();
                cmd.Parameters.Add(user);

                SqlParameter pass = new SqlParameter();
                pass.ParameterName = "@password";
                pass.Value = Hasher.HashString(password.Trim());
                cmd.Parameters.Add(pass);

                conn.Open();

                int count = (int)cmd.ExecuteScalar();

                if (count > 0) returnValue = true;
            }

Here is my web.config connectionstring

  <connectionStrings>
<add name="MembershipSiteConStr" connectionString="Data Source=dev-pc\;Initial Catalog=MembershipSite;User ID=test;Password=test" />

i've tested this SQL connection using server explorer and SQL managment and it all works.

here are some SP of what's going on;

在此处输入图片说明

here is evidence that the user and pass im putting in should work; The user is there:

在此处输入图片说明

that the SQL query works:

在此处输入图片说明

Change code of Adding Password Parameter as follow

 SqlParameter pass = new SqlParameter();
 pass.ParameterName = "@password";
 //pass.Value = Hasher.HashString(password.Trim());
 pass.Value = password.Trim(); 
 cmd.Parameters.Add(pass);

I think you need to set the provider name at connectionStrings

 <connectionStrings>
<add name="MembershipSiteConStr" connectionString="Data Source=dev-pc\;Initial Catalog=MembershipSite;User ID=test;Password=test" providerName="System.Data.SqlClient" />

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