6

I am making a call to a Web API that I wrote. I am working through the bugs on both sides and am getting a 500 error. I want to see that is in that error message to see what might be the problem. How do I find that?

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;
}

I don't see where that text might be stored so I can figure out what other bugs need to be fixed. How do I get that text?

Update: something I didn't clarify. I put a breakpoint on the WebAPI I am calling and the break point is never hit. However, when I call it from Poster, I hit the break point. The URL is correct.

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

2 回答 2

21

我能够进行更改以获取错误消息:

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

代替

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

然后我能够看到我的错误并修复它。

于 2013-05-06T19:28:46.860 回答
0

我正在调用我编写的 Web API。我想查看该错误消息中的内容,以查看可能是什么问题。

您可能希望将您拥有的代码放在PayrollApi.LeaveRequesttry-catch 块中,例如:

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 块中调用以捕获额外的错误:

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可以有这个消息:

响应状态码不表示成功:500 ({stack_trace_goes_here})。

于 2013-05-06T06:09:48.250 回答