John Steed
John Steed

Reputation: 629

Using JsonPatchDocument With PatchAsync In Blazor Client

In my Blazor Client project, I have the following code:

    @using Microsoft.AspNetCore.JsonPatch

    ...

    var doc = new JsonPatchDocument<Movie>()
         .Replace(o => o.Title, "New Title");

    await Http.PatchAsync("api/patch/" + MovieId, doc);

This won't compile with the following error:

Error CS1503 Argument 2: cannot convert from 'Microsoft.AspNetCore.JsonPatch.JsonPatchDocument' to 'System.Net.Http.HttpContent'

After some research, I've installed Newtonsoft.Json but I'm unsure how to configure the project to use it, or if indeed this is the correct solution for getting JsonPatchDocument working in a Blazor Project?

If JsonPatchDocument is not supported by Blazor, how can I implement a HTTP Patch request?

Upvotes: 1

Views: 1381

Answers (1)

benjamin
benjamin

Reputation: 1654

I just had a different but related issue. You are correct that you need to be using Newtonsoft.Json instead of System.Text.Json on the client application. Here is an extension method that will turn your JsonPatchDocument into an HttpContent.

 public static class HttpClientExtensions
 {
     public static async Task<HttpResponseMessage> PatchAsync<T>(this HttpClient client,
     string requestUri,
     JsonPatchDocument<T> patchDocument)
     where T : class
 {
     var writer = new StringWriter();
     var serializer = new JsonSerializer();
     serializer.Serialize(writer, patchDocument);
     var json = writer.ToString();

     var content = new StringContent(json, Encoding.UTF8, "application/json-patch+json");
     return await client.PatchAsync(requestUri, content);
 }

I know it's late but I hope it's helpful.

Upvotes: 3

Related Questions