JsonPatch學習
網址 http://jsonpatch.com/
參考資料 https://docs.microsoft.com/zh-cn/aspnet/core/web-api/jsonpatch?view=aspnetcore-3.1
jsonpatch 個人感覺就是簡化修改接口,就像給接口傳個命令一樣, replace Age 30;replace 就像命令, Age 就是參數,要修改的字段, 30 就是具體修改的值,jsonpatch 是通過json的方式來傳遞命令的,基本就是對json的 操作,增改刪,
支持的語言也比較廣泛,js 用法 http://jsonpatchjs.com/
例如 我們在QQ 中設置資料的時候, 是沒有保存按鈕的,選一個 或者編輯 都會 更新的,這種功能,我們不可能每次小改動就傳遞一個很大的實體去服務端修改,jsonpatch 就解決了這個問題
[{"op":"replace","path":"isopen","value":"true"}] 這個就即搞定,

頁面是沒有保存按鈕的,但是點擊復選框等都會保存我們的操作。
安裝2個包
Microsoft.AspNetCore.JsonPatch
Microsoft.AspNetCore.Mvc.NewtonsoftJson
注冊
services.AddControllers().AddNewtonsoftJson();
準備實體類和API接口
1 [ApiController] 2 [Route("jsonpatch")] 3 public class JsonPatchController : ControllerBase 4 { 5 public static List<User> _list; 6 private readonly ILogger<JsonPatchController> _logger; 7 8 public JsonPatchController(ILogger<JsonPatchController> logger) 9 { 10 _logger = logger; 11 _list = new List<User>(); 12 13 _list.Add(new User { Address=new List<Address> { new Address { City="廣州", Group="一組" } }, Id=1, Name="jet1" }); 14 _list.Add(new User { Address = new List<Address> { new Address { City = "深圳", Group = "2組" } }, Id = 2, Name = "jet2" }); 15 _list.Add(new User { Address = new List<Address> { new Address { City = "西安", Group = "3組" } }, Id = 3, Name = "jet3" }); 16 17 18 } 19 [Route("[action]/{id}")] 20 [HttpPatch] 21 public IActionResult UserOperation(int id, [FromBody] JsonPatchDocument<User> userDoc) 22 { 23 if (userDoc != null) 24 { 25 var user =_list.Where(x=>x.Id== id).FirstOrDefault(); 26 userDoc.ApplyTo(user, ModelState); 27 if (!ModelState.IsValid) 28 { 29 return BadRequest(ModelState); 30 } 31 //context.savechange() 32 return new ObjectResult(user); 33 } 34 else 35 { 36 return BadRequest(ModelState); 37 } 38 } 39 40 41 } 42 43 44 public class User 45 { 46 public int Id { get; set; } 47 public string Name { get; set; } 48 public List<Address> Address { get; set; } 49 } 50 public class Address 51 { 52 public string City { get; set; } 53 public string Group { get; set; } 54 }
postman 請求, Content-Type :application/json-patch+json
add
1 [ 2 { 3 "op": "add", 4 "path": "/Address/-", 5 "value": { 6 "City":"咸陽" 7 } 8 }, 9 { 10 "op": "add", 11 "path": "/Address/-", 12 "value": { 13 "City":"寶雞" 14 } 15 } 16 17 ]
remove
1 [ 2 { 3 "op": "remove", 4 "path": "/Address/", 5 "value": { 6 "City":"廣州" 7 } 8 } 9 10 ]
replace
1 [ 2 { 3 "op": "replace", 4 "path": "/Address/-", 5 "value": { 6 "City":"湛江" 7 } 8 } 9 10 ]
移動操作 將城市移動到了user name
1 [ 2 { 3 "op": "move", 4 "from":"/Address/0/City", 5 "path": "/Name" 6 } 7 8 ]
還有 copy test
test 操作通常用于在發生并發沖突時阻止更新。
浙公網安備 33010602011771號