2016-08-18 4 views
-1

이 함수를 실행하려고하면 ""System.InvalidCastException : 지정된 캐스트가 유효하지 않습니다. "오류가 발생합니다. C# 요청 처리기 오류 System.InvalidCastException : 지정한 캐스트가 유효하지 않습니다.

System.InvalidCastException: Specified cast is not valid. 
    at server.mihail.credits.HandleRequest() in F:\Users\Mihail\Documents\new-sentients-2016\server\mihail\credits.cs:line 34 
    at server.RequestHandler.HandleRequest(HttpListenerContext context) in F:\Users\Mihail\Documents\new-sentients-2016\server\RequestHandlers.cs:line 37 
    at server.Program.ProcessRequest(HttpListenerContext context) in F:\Users\Mihail\Documents\new-sentients-2016\server\Program.cs:line 156 

는 기능입니다 : 나는 그것을에서 최고의 내 이메일 주소와 매개 변수의 원조로 GUID를 매개 변수로 그것을 실행하려고 .

제발 도와주세요. 하루 종일 고치기 위해 노력하고 있습니다. 문제가 라인 cmd.Parameters.AddWithValue("@accId", (int) id);으로처럼 그 캐스트 유일한 라인으로 귀하가 제공 한 제한된 정보를 바탕으로

class credits : RequestHandler 
{ 
    protected override void HandleRequest() 
    { 
     string status = "403"; 
     using (Database db = new Database()) 
     { 
     NameValueCollection query = HttpUtility.ParseQueryString(Context.Request.Url.Query); 
     MySqlCommand cmd = db.CreateQuery(); 
     cmd.CommandText = "SELECT id FROM accounts WHERE [email protected]"; 
     cmd.Parameters.AddWithValue("@uuid", query["guid"]); 
     object id = cmd.ExecuteScalar(); 
     if (id != null) 
     { 
     int amount = int.Parse(query["aid"]); 
     cmd = db.CreateQuery(); 
     cmd.CommandText = "UPDATE stats SET credits = credits + @amount WHERE [email protected]"; 
       cmd.Parameters.AddWithValue("@accId", (int) id); 
       cmd.Parameters.AddWithValue("@amount", amount); 
       int result = cmd.ExecuteNonQuery(); 
       if (result > 0) 
        status = "400"; 
       else 
        status = "500"; 
      } 
      else 
       status = "404"; 
     } 
     byte[] res = Encoding.UTF8.GetBytes(
      status); 
     Context.Response.OutputStream.Write(res, 0, res.Length); 
    } 
} 
+2

어떤 라인이 예외를 던지고 있습니까? 나는 그들을 계산하지 않을거야 :) – SledgeHammer

+0

@ LaneL 당신은 실제로 박스 int 경우 수 있습니다. 문제가 무엇인지 추측 할 필요가 없습니다. OP가 어떤 라인에서 예외를 throw하는지 알려주지 않으면 안됩니다. – Jakotheshadows

답변

1

, 그것은 보인다.

데이터베이스의 accounts.id 열의 유형을 확인하십시오. INT이 아닌 것으로 의심되므로 유형 (괄호 안의 유형)을 유형으로 변경해야합니다. SMALLINTTINYINTbyte (또는 sbyte)이며, BIGINTlong이며, C#에서 short, 당신은 무엇을 MEDIUMINT지도에 볼 수있는 문서를 볼 필요가 싶지만, 아마 int 그것.

1

나는 ID 앞에 (int) 있지만 (ID) 전에 (int) 만 제거 할 필요가없는 것으로 나타났습니다.

그래서 나는이 오류를 던지고있는 줄 내가 추측하고

cmd.Parameters.AddWithValue("@accId", id); 
0

와 함께이 라인

cmd.Parameters.AddWithValue("@accId", (int) id); 

을 대체 할 수 있습니다.

id 변수를 사용하여 object에서 int로 캐스트가 발생하는 것을 볼 수 있습니다.

다음은

[TestMethod] 
    public void ObjectToInt() 
    { 
     object a = 2; 
     object b = "3"; 
     int aa = (int)a; 
     int bb = (int)b; // this throws the same error 
     var x = 1; 
    } 

어쩌면 INT와 INT 널 (NULL) 할 문제 보여줄 수 있을까? 또는 객체의 가치가 실제로 무엇인지 확인하십시오.

희망이 도움이됩니다.