zoukankan      html  css  js  c++  java
  • ASP.NET Core JSON Patch使用简述

    简述

    JSON Patch 是一种格式,用于指定要应用于资源的更新。 JSON Patch文档有一个** 操作数组。 每个操作标识一种特定类型的更改。 此类更改的示例包括添加数组元素或替换属性值。

    JSON 数据示例

    {
      "baz": "qux",
      "foo": "bar"
    }
    

    JSON Patch 数据示例

    [
      { "op": "replace", "path": "/baz", "value": "boo" },
      { "op": "add", "path": "/hello", "value": ["world"] },
      { "op": "remove", "path": "/foo" }
    ]
    

    在上述 JSON 中:

    • op 属性指示操作的类型。
    • path 属性指示要更新的元素。
    • value 属性提供新值。

    使用JSON Patch 之后的资源结果

    {
      "baz": "boo",
      "hello": ["world"]
    }
    

    下表显示了 JSON 修补程序规范中定义的支持操作:

    Operation 说明
    add 添加属性或数组元素。 对于现有属性:设置值。
    remove 删除属性或数组元素。
    replace 与在相同位置后跟 add 的 remove 相同。
    move 与从后跟 add 的源到使用源中的值的目标的 remove 相同。
    copy 与到使用源中的值的目标的 add 相同。
    test 如果 path 处的值 = 提供的 value,则返回成功状态代码。

    在Asp.net Core 中使用 JSON Patch

    引用包

    Microsoft.AspNetCore.JsonPatch
    

    使用方式

    在API 控制器中,JSON Patch操作方法:

    • 在方法中使用HttpPatch特性标签
    • 接受 JsonPatchDocument<T>,通常带有 [FromBody]
    • 调用ApplyTo()方法应用更改

    API 控制器代码如下:

    [Route("")]
    [HttpPatch]
    public async Task<IActionResult> Patch([FromBody]JsonPatchDocument<AppUser> jsonPatch)
    {
        if (jsonPatch != null)
        {
            var user = await _userContext.Users.FirstOrDefaultAsync(s => s.Id == UserIdentity.UserId);
            jsonPatch.ApplyTo(user);
            _userContext.SaveChanges();
            return Json(user);
        }
        else
        {
            return BadRequest(ModelState);
        }
    }
    

    PostMan 请求示例

    • 请求方式为:PATCH
    • Content-Type:application/json
    [
        {
            "op":"replace",
            "path":"/Company",
            "value":"上海无敌土豆科技有限公司"
        },
        {
            "op":"replace",
            "path":"/Title",
            "value":"小土豆"
        }
    ]
    

    数组处理方式

    [
        {
            "op":"replace",
            "path":"/Properies",
            "value":
            [
                {
                    "Key":"fin_stage",
                    "Value":"A+轮",
                    "Text":"A+轮"
                },
                {
                    "Key":"fin_stage",
                    "Value":"C轮",
                    "Text":"C轮"
                }
    
    
            ]
        }
    ]
       
    

    可能会遇到下面的错误

    {
        "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
        "title": "One or more validation errors occurred.",
        "status": 400,
        "traceId": "|fcde218-4047aa49553937bd.",
        "errors": {
            "$": [
                "The JSON value could not be converted to Microsoft.AspNetCore.JsonPatch.JsonPatchDocument`1[User.API.Entity.Models.AppUser]. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
            ]
        }
    }
    

    遇到上述错误的原因为程序无法正常解析该json,因为没有找到NewtonsoftJson包的依赖;关于微软为何要移除该包的依赖,主要是为了提升执行效率;System.Text.Json作为微软内置json处理,效率更高更快,但是目前大部分主流的包还是使用的NewtonsoftJson开发

    官方文档描述如下:

    ASP.NET Core 3.0 之前的版本中,默认设置使用通过 Newtonsoft.Json 包实现的 JSON 格式化程序。 在 ASP.NET Core 3.0 或更高版本中,默认 JSON 格式化程序基于 System.Text.Json。 Newtonsoft.Json通过安装 Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet 包并在中进行配置,可获得对基于的格式化程序和功能的支持 Startup.ConfigureServices

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers()
            .AddNewtonsoftJson();
    }
    

    官方文档地址:https://docs.microsoft.com/zh-cn/aspnet/core/web-api/advanced/formatting?view=aspnetcore-3.1#add-newtonsoftjson-based-json-format-support

  • 相关阅读:
    nessus 安装
    firefox SSL_ERROR_RX_RECORD_TOO_LONG burpsuit 报错 解决方案
    Vmware 15 新建虚拟机黑屏
    esp8266 IOT Demo 固件刷写记录
    elk + suricata 实验环境详细安装教程
    停更申明
    求二叉树的深度
    方差
    链表的基本排序
    正态分布及3Sigma原理
  • 原文地址:https://www.cnblogs.com/imtudou/p/13664084.html
Copyright © 2011-2022 走看看