如何使用 Patch 方法用文件更新实体

问题描述

我有一个包含一些图像的实体,我想使用 HttpPatch 方法更新它。

要创建新样式,我使用以下方法

[HttpPost]
public async Task<IActionResult> CreateStyleAsync([FromForm] StyleFiles styleFiles,[FromForm] StyleDTO style)

现在我正在尝试创建一种使用 HttpPatch 方法更新此样式的方法。我试过了,但没有选项可以在 Swagger 上上传文件

[HttpPatch("{styleId}")]
public async Task<IActionResult> PatchStyleAsync([FromForm] StyleFiles styleFiles,Guid styleId,[FromBody] JsonPatchDocument styleDto)

这是我在 Swagger 上看到的: Patch method on Swagger

这是 DTO:

public class StyleDTO
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string PreviewImage { get; set; }
}

这是 StyleFiles 类:

public class StyleFiles
{
    public IFormFile Image { get; set; }
}

我正在考虑制作两个单独的端点,一个用于更新文件,另一个用于更新实体本身。但我不想那样做。

解决方法

[FromForm][FromBody] 不能同时用作参数。因为它们的内容类型不同。 [FromForm] 将序列化表单中的值,但 [FromBody] 传递 json 数据。因此,您必须创建两个独立的端点。

我不知道 StyleFilesStyleDTO 之间是否存在冲突。您还可以创建单独的类来集成它们。

public class ViewModel
{
    public StyleDTO styleDTO { get; set; }
    public StyleFiles styleFiles { get; set; }
}

控制器

    [HttpPatch("{styleId}")]
    public async Task<IActionResult> PatchStyleAsync([FromForm] ViewModel viewModel)
    {
        return Ok();
    }

enter image description here