使用存储过程验证

时间:2014-03-19 16:46:17

标签: c# sql

我已经在SQL中编写了用于用户身份验证的存储过程,如何在我的c#.Net代码中获取此过程的返回值以使用户能够登录?

create procedure userLogin_proc
@userName nvarchar(45),
@passCode nvarchar(20)

as
begin

select userName,passCode from userLogin where username = @userName and passCode = @passCode
end

3 个答案:

答案 0 :(得分:3)

使用output参数返回userid,如果登录成功,将返回用户ID,否则返回0

create procedure userLogin_proc
@userName nvarchar(45),
@passCode nvarchar(20)
@UserId int=0 OUTPUT
as
begin

select @UserId =id from userLogin where username = @userName and passCode = @passCode
end

并在C#端在ExecuteReader之后执行此操作:

SqlDataReader reader=cmd.ExecuteReader();
int UserId = (int)cmd.Parameters["@UserId"].Value;

您可以在此处阅读有关输出参数的更多信息:

http://www.codeproject.com/Questions/136351/How-to-retrieve-output-parameter-from-Store-proced

答案 1 :(得分:1)

将其更改为SELECT COUNT(1) FROM userLogin....,然后在SqlDataReader对象上使用ExecuteScalar()

作为旁注,将密码以明文形式存储在数据库中并不是一个好主意,而是将它们哈希,最好是使用盐值。

答案 2 :(得分:1)

不要将纯文本密码存储在数据库中。查找散列方法。在下面的示例中,我使用SHA256

class User
{
    public string UserName { get; private set; }
    public string Password { get; private set; }
    public User(string userName, string plainTextPassword)
    {
        this.UserName = userName;
        this.Password = GetHash(plainTextPassword);
    }
    public string GetHash(string toHash)
    {
        return BitConverter.ToString(new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(toHash))).Replace("-", string.Empty);
    }
    public void Save() { /* Save UserName and the Hashed Password to database */ }
    public bool ValidateLogin(string userNameEntered, string passwordEntered)
    {
        string userName; string password = string.Empty;
        string ConnectionString = "Your Connection String";
        using (SqlConnection con = new SqlConnection(ConnectionString))
        {
            con.Open();
            string CommandText = "SELECT UserName, Password FROM userLogin WHERE Username = @UserName";
            using (SqlCommand cmd = new SqlCommand(CommandText))
            {
                cmd.Connection = con;
                cmd.Parameters.Add("@Username", SqlDbType.VarChar, 20).Value = userNameEntered;
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    userName = rdr["UserName"].ToString();
                    password = rdr["Password"].ToString();
                }
            }
        }
        if (password.Equals(GetHash(passwordEntered))) return true;
        return false;
    }
}

此示例显示了散列的粗略示例以及从数据库中检索。