微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何为Web API PATCH方法构造有效负载?

如何解决如何为Web API PATCH方法构造有效负载?

我有一个用.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'
}

谢谢。

解决方法

由于您的问题似乎是如何为客户端创建此有效负载以传递给您的api,所以我建议使用模型类来表示您的有效负载:

//Model class to represent one object in payload
public class MyPayload
{
    [JsonProperty("op")]
    public string Op {get; set;}
    
    [JsonProperty("path")]
    public string Path {get; set;}
    
    [JsonProperty("value")]
    public string Value {get; set;}
}

然后在您的示例代码中,更改为:

var AccountPayload = new List<MyPayload>
{
   new MyPayload() { Op = "replace",Path = "/Name",Value = "Test111" }
};
,

我会尝试使用JObject而不是JsonPatchDocument

,

您可以使用class ServiceAdmin extends AbstractAdmin protected function configureFormFields(FormMapper $formMapper): void { $formMapper ->add('serviceName',EntityType::class,[ //here 'class' => 'App:Service','choice_label' => 'serviceName',]) ->add('identifier') ->add('password') ->add('comment') ; } nuget包中的JsonPatchDocument<T>来构建补丁

Microsoft.AspNetCore.JsonPatch

这假定您拥有var patchDoc = new JsonPatchDocument<Account>(); patchDoc.Replace(p => p.Name,"TEST111"); Console.WriteLine(JsonConvert.SerializeObject(patchDoc)); // outputs what you'd expect 类(具有Account属性)作为客户端上的强类型对象。如果没有,可以按如下方式使用非通用变体:

Name
,

过去也有Patch问题。在我的情况下,这些是通过X-Http-Method-Override标头解决的:

        if (request.Method == Method.PATCH)
        {
            request.AddHeader("X-Http-Method-Override","PATCH");
            request.Method = Method.POST;
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。