![](/img/trans.png)
[英]Issue with HttpClient.PostAsJsonAsync Not Working from ASPX
[英]How do I determine what is the issue with a 500 error on a HttpClient.PostAsJsonAsync call?
我正在調用我編寫的Web API。 我正在解決雙方的錯誤,並收到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上放了一個斷點,斷點永遠不會被擊中。 然而 ,當我從海報中調用它時,我達到了斷點。 網址是正確的。
public HttpResponseMessage Post([FromBody]LeaveRequest value)
{
if (ModelState.IsValid)
{
// code here
}
}
我能夠進行更改以獲取錯誤消息:
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})。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.