2016-10-26 13 views
-1

에 로그인하기위한 간단한 api를 만들려고 시도하지만 데이터가 데이터베이스에없는 경우에도 내 검사 조건은 true을 반환합니다. 여기 login.csC# rest에서 코드화가 거짓 일 때 true를 반환하면

public string username { get; set; } 
public string password { get; set; } 

public string AddEmployees(Login Emp) 
{ 
    try 
    { 
     SqlDataReader reader = null; 
     SqlCommand com; 
     SqlConnection con = new SqlConnection(@"Data Source=DOTNET;Initial Catalog=edin;Integrated Security=True;Pooling=False"); 

     com = new SqlCommand("Select count(*) from data where name='" + username + "' and phone='" + password + "'", con); 
     con.Open(); 
     reader = com.ExecuteReader(); 
     if (reader.Read()) 
     { 
      return "success";//returns this always 
     } 
     else 
     { 
      return "error"; 
     } 
     con.Close(); 
    } 
    catch (Exception aa) 
    { 
     return aa.ToString(); 
    } 

} 

및 내 모델 내 잘못이다 Controller

public string AddEmployees(Login Emp) 
{ 
    Login employe = new Login(); 
    var response = employe.AddEmployees(Emp); 
    return response; 
} 

..? 또는 일부 코드가 누락되었습니다. 아무도 도와주세요

+0

목록에 넣은 다음 계산하면 아무 것도 발견되지 않더라도 카운트가 0을 반환 할 가능성이 있습니까? –

+5

'SELECT COUNT (*) ...'는 항상 값 (0 또는 1)을 반환하므로'if (reader.Read())'는 항상 'true'가됩니다. –

+0

ExecuteScalar가 이 경우 ! – mybirthname

답변

0

dont use count. 대신 필드를 선택하십시오. HasRows()가 찾고있는 것을 도움이 될 것입니다. 이 시도 :

SqlDataReader reader = null; 
    SqlCommand com; 
    SqlConnection con = new SqlConnection(@"Data Source=DOTNET;Initial Catalog=edin;Integrated Security=True;Pooling=False"); 

    com = new SqlCommand("Select name from data where name='" + username + "' and phone='" + password + "'", con); 
    con.Open(); 
    reader = com.ExecuteReader(); 


    return reader.HasRows() ? "success" : "error"; 
    con.Close(); 
1

실제 행 자체를 선택하려고하면 행이 발견되면 true, 그렇지 않으면 false을 반환하는 코드가 예상대로 작동합니다.

당신은 더 일치하는 레코드가 발견되지 않은 경우 0를 반환하는 것입니다, 이는 비록 Select count(*)을하고있는, 그래서 반환 뭔가은 항상있다.

ExecuteReader 대신 ExecuteScalar()을 사용해보세요. 성공 또는 실패를 판별하는 데 사용할 수있는 단일 값 (행 수)을 리턴합니다.

int rowCount = com.ExecuteScalar(); 
return (rowCount == 0) ? "failure" : "success"; 
+3

여기에 나와있는 문제와 관련이 없지만 쿼리를 매개 변수화하는 습관이 생깁니다 (안전성과 버그 도입 가능성 감소).이 [documentation] (https://msdn.microsoft. com/ko-kr/library/system.data.sqlclient.sqlcommand.parameters (v = vs.110) .aspx)는 좋은 시작점을 제공합니다. –

0

당신은이 :

Select count(*) from data where name= ... 

그래서 당신은 항상 지정된 사용자가 DB에 존재하지 않는 경우에도, 결과를해야합니다. 그래서 당신은 항상 reader.Read() true를 얻을 것입니다.

반면에 나는 결과 문자열을 반환하는 것이 좋은 선택이 아니라는 것을 알고 있습니다. 그리고 SQL 쿼리에서 연결을 피하는 것을 잊지 마십시오. 오히려 그 SQL 쿼리 때문에 생성 쿼리의 종류 :

Select count(*) from data where name='" + username + "' and phone='" + password + "'" 

때문에 SQL 주입 때문에, 매우 위험합니다.

관련 문제