如何结合JsonPatchDocument、FromForm与IFormFile实现Movie模型部分更新?
使用JsonPatchDocument实现含图片的Movie部分更新方案
核心思路
因为要同时处理JSON格式的Patch操作和文件上传,无法直接通过[FromBody]绑定JsonPatchDocument,需要分两步处理:先接收Patch操作的JSON字符串并反序列化为JsonPatchDocument,再单独接收图片文件,将其转为字节数组后手动添加到Patch操作中,最后统一应用到实体。
代码实现
1. Movie模型(参考你的定义)
public class Movie { public int Id { get; set; } public string Title { get; set; } public byte[] img_movie { get; set; } // 其他业务字段... }
2. 改造后的MoviesController Patch接口
using Microsoft.AspNetCore.JsonPatch; using Newtonsoft.Json; // 需安装Newtonsoft.Json NuGet包 using System.IO; [HttpPatch("{id}")] public async Task<IActionResult> PatchMovie(int id, [FromForm] string patchDocument, [FromForm] IFormFile? imageFile) { // 获取目标电影实体 var targetMovie = await _dbContext.Movies.FindAsync(id); if (targetMovie == null) return NotFound(); // 反序列化Patch操作文档 var patch = JsonConvert.DeserializeObject<JsonPatchDocument<Movie>>(patchDocument); if (patch == null) return BadRequest("无效的Patch操作文档"); // 处理上传的图片:转为字节数组并添加到Patch操作 if (imageFile != null && imageFile.Length > 0) { using var memoryStream = new MemoryStream(); await imageFile.CopyToAsync(memoryStream); var imageBytes = memoryStream.ToArray(); patch.Replace(movie => movie.img_movie, imageBytes); } // 应用Patch操作到实体 patch.ApplyTo(targetMovie, ModelState); // 验证模型并保存 if (!ModelState.IsValid) return BadRequest(ModelState); await _dbContext.SaveChangesAsync(); return Ok(targetMovie); }
Postman请求配置
- 请求方法:
PATCH - 请求URL:
http://your-api-domain/api/movies/{movieId} - Body选择
form-data,添加两个字段:- 字段名:
patchDocument,类型选Text,值为JSON格式的Patch操作,示例:[ { "op": "replace", "path": "/title", "value": "更新后的电影名称" } ] - 字段名:
imageFile,类型选File,选择本地图片文件上传
- 字段名:
注意事项
- 若项目使用
System.Text.Json而非Newtonsoft.Json,将反序列化代码替换为JsonSerializer.Deserialize<JsonPatchDocument<Movie>>(patchDocument)即可 - 大文件场景建议添加文件大小限制,避免内存溢出
- 可额外校验Patch操作的合法性,防止恶意字段修改
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

