字符串必须正好是一个字符长c#错误

时间:2018-07-24 07:32:51

标签: c# asp.net

如何解决此错误字符串必须正好一个字符长。 我正在共享此功能,请对此进行调查并解决此问题。

我正在突出显示行,您可以看到此行。以及我们能否将char转换为字符串或其他内容,该如何解决这个问题。

功能

public DataTable mlogin(string username, string password)
{
    string constring = ConfigurationManager.ConnectionStrings["Real"].ConnectionString;

    SqlConnection con = new SqlConnection(constring);
    password = Cryptographer.Encrypt(password);
    con.Open();

    if ( char.IsNumber( Convert.ToChar(username)))   //String must be exactly one character long
    {
        cmd = new SqlCommand("select MD.MembershipID, MembershipName, address, ISNULL(FD.FileID,'') as FileID,ISNULL(Sec.SectorName, '') as SectorName, ISNULL(I.PlotNo, '') as PlotNo, MD.ClientPic from MemberMaster MM " +
            " inner join MembersDetail MD on MD.MemberShipID = MM.MemberShipID and MD.Srno = 1 " +
            " inner join MasterFileDetail FD on FD.MembershipID = MM.MemberShipID and FD.IsOwner = 1 and FD.IsTransfered = 1 " +
            " inner join MasterFile FM on FM.FileID = FD.FileID and FM.Cancel = 0 " +
            " inner join Sectors Sec on Sec.Phase_ID = FM.PhaseId and Sec.Sector_ID = FM.Sector_ID " +
            " inner join PlotsInventory I on I.Phase_ID = FM.PhaseId and I.Plot_ID = FM.Plot_ID " +
            " where MM.MemberShipID = '" + username + "' and MM.IsApproved = 1 and RTRIM(MM.LoginPwd) = '" + password + "' and MM.IsActive = 1 " +
            " order by FD.FileID", con);
    }
    else
    {
        cmd = new SqlCommand("select User_Id, User_Name,User_Type, Group_Id from BriskSecurity.dbo.Users where User_Login='" + username + "' and User_password='" + password + "' ", con);
    }

        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@MembershipID",username);
        cmd.Parameters.AddWithValue("@LoginPwd", password);
        DataTable mDT_User = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(mDT_User);
        con.Close();
        return mDT_User;

    }

1 个答案:

答案 0 :(得分:6)

您所做的根本上是错误的。

考虑用户名“ John”。您可以将4个字符串转换为单个字符吗?否。您不能使用它来验证整个用户名是否为数字。

相反,您有两个选择:

(1)验证用户名的每个字符为数字:

if (username.All(c => char.IsNumber(c)))
{

(2)将其解析为数字(假设可以将其表示为数字,并且前导零并不重要)

if (int.TryParse(username, out var usernameAsInt))
{

接下来,我建议查看参数化的SQL查询。

想象一下以下查询:

"SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'"

如果我的用户名是' OR username = 'administrator'; --,该怎么办?查询变为:

SELECT * FROM users WHERE username = '' OR username = 'administrator'; -- ' AND password = ''

-之后的所有内容均会成为注释。您可以了解有关参数化SQL查询here的更多信息。