You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合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请求配置

  1. 请求方法:PATCH
  2. 请求URL:http://your-api-domain/api/movies/{movieId}
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 06:52:40