1

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?

2
  • Did you try this: learn.microsoft.com/en-us/dotnet/api/… Commented May 23, 2020 at 15:27
  • @enet Thanks for replying, yes I did but that document doesn't describe how a JsonPatchDocument object can be used as the HttpContent parameter, or if such an object is supported within a Blazor Client project. Commented May 23, 2020 at 15:44

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.