【发布时间】:2021-01-20 10:01:27
【问题描述】:
我有一个用 .NET Core 编写的 Web API。
PATCH方法在参数中使用[FromBody]JsonPatchDocument:
[HttpPatch("{id}")]
public Account Patch(int id, [FromBody]JsonPatchDocument<Account> accountPath)
我能够从 Postman 或 Swagger UI 执行所有方法(GET、PUT、POST、PATCH),但我在从 .NET 客户端应用程序执行 PATCH 方法时遇到了困难。
这是我在 Swagger UI 或 Postman 上为 PATCH 方法传递给请求正文的内容:
[{"op": "replace","path": "/Name","value": "Test111"}]
如何在 .NET 客户端应用程序中传递上述有效负载?
当我执行以下代码时,它不会给我一个错误,但响应是
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
这是我的代码:
using System.Net.Http;
using Newtonsoft.Json;
using (var client = new HttpClient(handler))
{
var AccountPayload = new Dictionary<string, object>
{
{"Name", "TEST111"}
};
var content = JsonConvert.SerializeObject(AccountPayload);
var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://localhost:5001/api/myAPI/1");
request.Content = new StringContent(content, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
return response; //--> response = StatusCode: 400, ReasonPhrase: 'Bad Request'
}
谢谢。
【问题讨论】:
-
[{"op": "replace","path": "/Name","value": "Test111"}]是一个对象数组,在这个例子中,数组中的一个对象有3个属性:op、path和value,你的AccountPayload不匹配这种类型的json。所以它可能无法反序列化您在客户端中发送的json。 -
正确。如何为 Web API 创建此数组有效负载?
标签: c# json .net asp.net-web-api asp.net-core-webapi