2013-05-06 38 views
4

我正在調用我寫的Web API。我正在通過雙方的錯誤,並得到500錯誤。我想看看那個錯誤消息是否有問題。我如何找到?如何確定HttpClient.PostAsJsonAsync調用時出現500錯誤的問題?

using (var client = new HttpClient()) 
{ 
    var fooURL = Url.RouteUrl("PayrollApi", new { httproute = string.Empty, controller = "LeaveRequest" }, Request.Url.Scheme); 
    var repsonse = client.PostAsJsonAsync(fooURL, leaveRequest).Result; 
} 

我沒有看到文本可能存儲在哪裏,所以我可以找出需要修復的其他錯誤。我如何獲得該文本?

更新:我沒有說明。我在我打電話的WebAPI上放置了一個斷點,並且斷點從未被擊中。 但是,當我從海報中調用它時,我打到了轉折點。該URL是正確的。

public HttpResponseMessage Post([FromBody]LeaveRequest value) 
{ 
    if (ModelState.IsValid) 
    { 
     // code here 
    } 
} 

回答

0

I am making a call to a Web API that I wrote. I want to see that is in that error message to see what might be the problem.

你可能想要把你在try-catch塊在PayrollApi.LeaveRequest的代碼,類似:

public HttpResponseMessage LeaveRequest() 
{ 
    try { 
     // do something here 
    } 
    catch(Exception ex) { 
     // this try-catch block can be temporary 
     // just to catch that 500-error (or any unexpected error) 
     // you would not normally have this code-block 
     var badResponse = request.CreateResponse(HttpStatusCode.BadRequest); 
     badResponse.ReasonPhrase = "include ex.StackTrace here just for debugging"; 
    } 
} 

然後做一個try-catch塊內調用capture額外的錯誤:

using (var client = new HttpClient()) 
{ 
    // rest of your code goes here 
    try 
    { 
     var repsonse = client.PostAsJsonAsync(fooURL, leaveRequest).Result; 
    } 
    catch(HttpRequestException httpEx) 
    { 
     // determine error here by inspecting httpEx.Message   
    } 
} 

httpEx.Message能有這樣的消息:

Response status code does not indicate success: 500 ({stack_trace_goes_here}).

16

我能夠做出改變,以獲得錯誤消息:的

var repsonse = client.PostAsJsonAsync(fooURL, leaveRequest).Result.Content.ReadAsStringAsync(); 

代替

var repsonse = client.PostAsJsonAsync(fooURL, leaveRequest).Result; 

當時我能看到我的錯誤並修復它。

相關問題