0

我正在尝试向 Web API 方法发送 AJAX PATCH 请求,并让Marvin.JsonPatch识别修补对象。

到目前为止,我发送到服务器的所有内容都导致收到一个空请求。

Web API 控制器方法如下所示:

public async Task<IHttpActionResult> Update(long orderId, JsonPatchDocument<Order> patchedOrder)

我正在使用HttpClient这样的方式发布(不能async在此应用程序中使用)...

var patchDoc = new JsonPatchDocument<Order>();
patchDoc.Replace(e => e.Price, newPrice);
patchDoc.Replace(e => e.WordCount, newWordCount);

var request = new HttpRequestMessage(new HttpMethod("PATCH"), uri)
              {
                  Content = new StringContent(JsonConvert.SerializeObject(patchDoc),
                                              System.Text.Encoding.Unicode,
                                              "application/json")
              };

HttpResponseMessage response;
using (var client = new HttpClient(...))
{
    response = client.SendAsync(request).GetAwaiter().GetResult();
}

但是当控制器是它时,patchedOrder参数是null.

在控制器上调试时,我也尝试过

var s = await Request.Content.ReadAsStringAsync();

但这会返回一个空字符串 - 谁能解释为什么?

更新:
这是传递给 HttpClient 时 JsonPatch 文档的内容...

{
    "Operations": [{
        "OperationType": 2,
        "value": 138.7,
        "path": "/price",
        "op": "replace"
    },
    {
        "OperationType": 2,
        "value": 1320,
        "path": "/wordcount",
        "op": "replace"
    }],
    "ContractResolver": {
        "DynamicCodeGeneration": true,
        "DefaultMembersSearchFlags": 20,
        "SerializeCompilerGeneratedMembers": false,
        "IgnoreSerializableInterface": false,
        "IgnoreSerializableAttribute": true,
        "NamingStrategy": null
    },
    "CaseTransformType": 0
}
4

1 回答 1

1

在 Marvin.JsonPatch 开发过程中的某个地方,JsonPatchDocument<T>使用了一个应用自定义 JSON 序列化程序的属性进行了注释:

[JsonConverter(typeof(JsonPatchDocumentConverter))]

此转换器使您能够调用JsonConvert.SerializeObject()此类补丁文档并实际生成补丁文档,而不是JsonPatchDocument<T>CLR 对象的表示。

将 Marvin.JsonPatch 和 Newtonsoft.Json 升级到最新版本,序列化应该会成功。

于 2018-09-26T13:15:20.147 回答