C# 如何确定HttpClient.PostAsJsonAsync调用中出现500错误的问题?
我正在调用我编写的Web API。我正在处理双方的错误,得到了500个错误。我想查看错误消息中的内容,以了解可能存在的问题。我怎么找到它C# 如何确定HttpClient.PostAsJsonAsync调用中出现500错误的问题?,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,我正在调用我编写的Web API。我正在处理双方的错误,得到了500个错误。我想查看错误消息中的内容,以了解可能存在的问题。我怎么找到它 using (var client = new HttpClient()) { var fooURL = Url.RouteUrl("PayrollApi", new { httproute = string.Empty, controller = "LeaveRequest" }, Request.Url.Scheme); var repso
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;
}
我不知道文本可能存储在哪里,所以我可以找出需要修复的其他bug。我怎样才能得到那条短信
更新:有些事情我没有澄清。我在我调用的WebAPI上设置了一个断点,而断点永远不会被击中。然而,当我从海报上调用它时,我达到了临界点。URL是正确的
public HttpResponseMessage Post([FromBody]LeaveRequest value)
{
if (ModelState.IsValid)
{
// code here
}
}
我正在调用我编写的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})
我可以进行更改以获取错误消息:
var repsonse = client.PostAsJsonAsync(fooURL, leaveRequest).Result.Content.ReadAsStringAsync();
而不是
var repsonse = client.PostAsJsonAsync(fooURL, leaveRequest).Result;
然后我就可以看到我的错误并修复它