0

My API has a method of type Patch that I need to call from the client. This method is:

[HttpPatch("{id}")]
public StatusCodeResult Patch(int id, [FromBody]JsonPatchDocument<Reservation> patch)
{
    Reservation res = Get(id);
    if (res != null)
    {
        patch.ApplyTo(res);
        return Ok();
    }
    return NotFound();
}

I am trying to call it from my client whose code is:

[HttpPost]
public async Task<IActionResult> UpdateReservationPatch(int id, Reservation reservation)
 {
     using (var httpClient = new HttpClient())
     {
         var request = new HttpRequestMessage
         {
             RequestUri = new Uri("http://localhost:8888/api/Reservation/" + id),
             Method = new HttpMethod("Patch"),
             Content = new StringContent("[{ \"op\":\"replace\", \"path\":\"Name\", \"value\":\"" + reservation.Name + "\"},{ \"op\":\"replace\", \"path\":\"StartLocation\", \"value\":\"" + reservation.StartLocation + "\"}]", Encoding.UTF8, "application/json")
         };

         var response = await httpClient.SendAsync(request);
     }
     return RedirectToAction("Index");
 }

I am failing to do so and getting error.

StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers: { Server: Microsoft-IIS/10.0 X-Powered-By: ASP.NET Date: Tue, 28 Jul 2020 12:25:24 GMT Content-Type: application/problem+json; charset=utf-8 Content-Length: 370 }}

What can be the problem?

Nemanja Todorovic
  • 2,521
  • 2
  • 19
  • 30
yogihosting
  • 5,494
  • 8
  • 47
  • 80
  • Do you receive any response body? Sometimes it can tell you what the error is. – juunas Jul 28 '20 at 12:28
  • Yes i received 400 error and the description is listed in the question itself. – yogihosting Jul 28 '20 at 12:29
  • Are you using the code from [here](https://learn.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-3.1#json-patch-addnewtonsoftjson-and-systemtextjson) to register the JSON Patch support? – Kirk Larkin Jul 28 '20 at 12:31
  • @KirkLarkin no, is it necessary? Because when I made the exact same code in asp.net core 2.0 then it worked right away. It is in asp.net 3.1 that it is not working. – yogihosting Jul 28 '20 at 12:34
  • 2
    3.0+ uses System.Text.Json (by default), which doesn't support JSON Patch. You can either switch entirely to Json.NET, or use that code to add Json.NET _only_ for the JSON Patch support. – Kirk Larkin Jul 28 '20 at 12:35
  • @KirkLarkin great. Your link solved my problem. – yogihosting Jul 28 '20 at 12:41

0 Answers0