我如何确定什么是问题与HttpClient上的500错误.PostAsJsonAsync电话

本文关键字:上的 错误 PostAsJsonAsync 电话 HttpClient 何确定 什么 问题 | 更新日期: 2023-09-27 18:12:10

我正在调用我编写的Web API。我正在通过双方的bug工作,并得到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上设置了一个断点,并且断点永远不会被击中。然而,当我从Poster调用它时,我碰到了断点。URL正确

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

我如何确定什么是问题与HttpClient上的500错误.PostAsJsonAsync电话

我可以做一个更改来获得错误消息:

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

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

我可以看到我的错误并修复它

我正在调用我编写的Web API。我想看到的是在错误消息中查看可能出现的问题。

您可能希望将PayrollApi.LeaveRequest中的代码放在try-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}) .