在Blazor客户端中将JsonPatchDocument与PatchAsync一起使用

在我的Blazor客户项目中,我有以下代码:

    @using Microsoft.AspNetCore.JsonPatch

    ...

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

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

这不会编译并出现以下错误:

错误CS1503参数2:无法从中转换   'Microsoft.AspNetCore.JsonPatch.JsonPatchDocument'   到'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?

评论
  • yeum
    yeum 回复

    请尝试以下操作:

    • Use IHttpClientFactory

    • Use HttpRequestMessage, something like the following:

      `var request = new HttpRequestMessage(new HttpMethod("PATCH"), url) { Content = stringContent };

      // Note sure about this as it is automatically being set by the // AuthorizationMessageHandler // request.Headers.Authorization = authorization;

      try { response = await client.SendAsync(request); } catch (HttpRequestException ex) {

      }`

      This was all from my weak memory. This, I believe, is the direction.

    希望这可以...

  • vvelit
    vvelit 回复

    错误非常明显。 JsonPatchDocument是旨在存储和应用补丁程序的对象。它不(直接)适合运输。

    这可能可行的唯一方法是:

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

    Note that I didn't try this. But I would guess that the normal System.Text.Json ought to work. The directions for using NewtonSoft are intended for the server part.