2015-01-11 3 views
0

WCF 서비스를 개발 중입니다. 데이터베이스에서 쿼리 한 후 하나의 개체를 반환하는 메서드가 있습니다.WCF - 기본 연결이 닫혔습니다 : 수신시 예기치 않은 오류가 발생했습니다.

현재 사용자 개체가 데이터로 채워진 경우 웹 서비스가 올바른 json 응답을 반환합니다. 그러나 사용자 개체가 데이터베이스의 데이터로 초기화되지 않은 경우 (데이터가 특정 ID에 대해 존재하지 않음) 다음과 같은 오류가 발생합니다.

"The underlying connection was closed: An unexpected error occurred on a receive." 

기존 코드 :

public static User GetUserById(int userId, string dbConnection) 
    { 
     var userClass = new User(); 
     using (var connection = new SqlConnection(dbConnection)) 
     { 
      connection.Open(); 
      var sqlCommand = new SqlCommand("GetUserById", connection); 

      sqlCommand.Parameters.Add(new SqlParameter("@UserId", SqlDbType.Int)); 
      sqlCommand.Parameters["@UserId"].Value = userId; 
      sqlCommand.CommandType = CommandType.StoredProcedure; 
      var reader = sqlCommand.ExecuteReader(); 
      while (reader.Read()) 
      { 
       userClass = FillUserObject(reader); 

      } 
      connection.Close(); 
      reader.Close(); 
     } 
     return userClass; 
    } 


    [OperationContract] 
    [WebGet(UriTemplate = "GetUserById?userId={userId}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] 
    User GetUserById(int userId); 

나는 원인을 찾을 수 없습니다입니다. 스택 추적도 작동하지 않습니다.

어떤 도움이 필요합니까?

+0

데이터가 없어도 문제가 발생하기 때문에'FillUserObject (reader)'메소드를 보여줘야합니다. 이미 서비스를 디버그하려고 했습니까? – Filburt

+0

내 사용자 클래스에 datetime 개체가 하나 있습니다. 내가 예상치 못한 가까운 오류를 얻는 것보다 그 객체에 가치를 전달하지 않으면. –

+0

그래서 nullable DateTime을 사용하여이 문제를 해결할 수 있습니까? – Filburt

답변

0

연결이 내부에 있습니다. connection.Close()를 명시 적으로 호출 할 필요가 없습니다. http://msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.110%29.aspx

+1

그건 사소한 개선이지만, OP 실제 문제를 해결하지 않을 것입니다. – Filburt

+0

내 사용자 클래스에 datetime 개체가 하나 있습니다. 내가이 예기치 않은 가까운 오류를 얻는 것보다 그 객체의 가치를 전달하지 않는다면. –

+0

그냥 약간의 개선은 있었지만 나중에 누군가에게 도움이 될 수 있기 때문에 그 진술을 남기고 싶었습니다. – Mino

관련 문제