无法使用 ASP.Net Core 2 中的 IFormFile 对象上传照片,并出现空引用异常

Could not upload photo using IFormFile object in ASP.Net Core 2 with null reference expception

我尝试使用邮递员插件 IFormFile 上传照片。但是 API 没有从请求正文中获取文件对象。我尝试使用和不使用 [FromBody].

[HttpPost]
public async Task<IActionResult> Upload(int vId, IFormFile fileStream)
{
    var vehicle = await this.repository.GetVehicle(vId, hasAdditional: false);
    if (vehicle == null)
        return NotFound();
    var uploadsFolderPath = Path.Combine(host.WebRootPath, "uploads");
    if (!Directory.Exists(uploadsFolderPath))
        Directory.CreateDirectory(uploadsFolderPath);
    var fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileStream.FileName);
    var filePath = Path.Combine(uploadsFolderPath, fileName);

    using (var stream = new FileStream(filePath, FileMode.Create))
    {
        await fileStream.CopyToAsync(stream);
    }

error 显示在这一行:

    var fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileStream.FileName);

我发现它没有获取文件,而我正在使用相同的密钥 "fileStream" 发送 image.jpg。顺便说一句,其他一切都很好。我找不到解决此问题的解决方案。如果有人可以帮助我,请告诉我。

FromBody 属性只能用于签名中的一个参数。 发送 int vId 的一个选项是通过查询字符串并使用 FromQuery 属性读取它。

像这样尝试

[HttpPost]
public async Task<IActionResult> Upload([FromQuery]int vId, [FromBody]IFormFile fileStream) 

然后将 POST 变为 url api/yourController?vId=123456789 正文包含 IFromFile

更新

由于表单数据将作为键值发送,请尝试创建一个包含键的模型并从正文中读取它

public class RequestModel
{
    public IFormFile fileStream { get; set; }
}

然后从正文中读取模型

[HttpPost]
public async Task<IActionResult> Upload([FromBody]RequestModel model) 

终于找到解决办法了。实际上问题出在旧版本的 Postman Tabbed Postman - REST Client chrome 扩展。在尝试使用新的邮递员应用程序后,它运行得非常好。感谢所有试图解决这个问题的人。这是结果:enter image description here