通过 Postman 将文件上传到 ASP.NET Core API 时出现错误 415

Error 415 while uploading a file through Postman to ASP.NET Core API

我正在尝试通过 ASP.NET 核心 API 上传文件。我的行动是:

[HttpPost]
[Route("{id}")]
public async Task<IActionResult> PostImage([FromBody] IFormFile file, [FromRoute] int id)
{
    if(file.Length > 0)
    {
        var fileName = Path.GetFileName(file.FileName);
        var fileExtension = Path.GetExtension(fileName);
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", "Image-" + id + "." + fileExtension);
        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }
        return Ok(fileName + fileExtension);
    }
    return NotFound("File not found!");
}

当我使用Postman检查其功能时,遇到错误415并且Visual Studio没有跳转到断点:

{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13", "title": "Unsupported Media Type", "status": 415, "traceId": "00-d411f8c099a9ca4db6fe04ae25c47411-dadd8cca7cc36e45-00" }

如何解决我的代码中的这个问题?

如果你想接收IFormFile,你需要post content-type=multiple/form-data,它来自表单数据,而不是正文。还要记得将 [FromBody] 更改为 [FromForm]

邮递员:

控制器:

[HttpPost]
[Route("{id}")]
public async Task<IActionResult> PostImage([FromForm] IFormFile file, [FromRoute] int id)

{}

如果您 post 来自正文的文件,也许您 post 一个字节数组。如果您需要将 IFormFile file 更改为 byte[] file