How to determine the problem with error 500 when calling HttpClient.PostAsJsonAsync?

I am referring to the web API that I wrote. I work on errors on both sides and get 500 errors. I want to see this error message in order to understand what might be the problem. How to find it?

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 this text can be saved, so I can figure out what other errors need to be fixed. How to get this text?

Update : I didn’t specify something. I set a breakpoint on the WebAPI that I call, and the breakpoint never hits. However, when I call it a poster, I hit a breakpoint. The correct URL.

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

I am referring to the web API that I wrote. I want to see this in this error message to see what might be the problem.

You can put the code that you have in PayrollApi.LeaveRequest in a try-catch block, for example:

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

Then make a call inside the try-catch block to fix this additional error:

 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 may have the following message:

The response status code does not indicate success: 500 ({Stack_trace_goes_here}).

0
source

I managed to make changes to get the error message:

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

instead

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

Then I was able to see my mistake and correct it.

+16
source

Source: https://habr.com/ru/post/1479292/


All Articles