IFormFile 总是 returns dotnet core 2.0 上的空值

IFormFile always returns Null value on dotnet core 2.0

我有一个 post 请求 PhotosController class。当我测试这段代码时,它总是 returns 一个空值。我没有看到文件详细信息。 基本上它得到 useridPhotoDto 并且它应该 return 照片。我使用 Cloudinary 服务来存储照片。我的 clodinary API 设置位于 appsettings.json 文件中,这些设置没有问题。当我调试代码时,问题出现在 if (file.Length > 0) 的位置。我猜没有文件。

这是我的 PhotoForCreationDto 文件:

public class PhotoForCreationDto
{
    public string Url { get; set; }
    public IFormFile File { get; set; }
    public string Description { get; set; }
    public DateTime DateAdded { get; set; }
    public string PublicId { get; set; }

    public PhotoForCreationDto()
    {
        DateAdded = DateTime.Now;
    }
}

这是我的 PhotosController 文件:

    [Authorize]
[Route("api/users/{userId}/photos")]
public class PhotosController : Controller
{
    private readonly IDatingRepository _repo;
    private readonly IMapper _mapper;
    private readonly IOptions<CloudinarySettings> _cloudinaryConfig;
    private Cloudinary _cloudinary;

    public PhotosController(IDatingRepository repo,
        IMapper mapper,
        IOptions<CloudinarySettings> cloudinaryConfig)
    {
        _mapper = mapper;
        _repo = repo;
        _cloudinaryConfig = cloudinaryConfig;

        Account acc = new Account(
            _cloudinaryConfig.Value.CloudName,
            _cloudinaryConfig.Value.ApiKey,
            _cloudinaryConfig.Value.ApiSecret
        );

        _cloudinary = new Cloudinary(acc);
    }

    [HttpGet("{id}", Name = "GetPhoto")]
    public async Task<IActionResult> GetPhoto(int id)
    {
        var photoFromRepo = await _repo.GetPhoto(id);

        var photo = _mapper.Map<PhotoForReturnDto>(photoFromRepo);

        return Ok(photo);
    }

    [HttpPost]
    public async Task<IActionResult> AddPhotoForUser(int userId, PhotoForCreationDto photoDto)
    {
        var user = await _repo.GetUser(userId);

        if (user == null)
            return BadRequest("Could not find user");

        var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

        if (currentUserId != user.Id)
            return Unauthorized();

        var file = photoDto.File;

        var uploadResult = new ImageUploadResult();

        if (file.Length > 0)
        {
            using (var stream = file.OpenReadStream())
            {
                var uploadParams = new ImageUploadParams()
                {
                    File = new FileDescription(file.Name, stream)
                };

                uploadResult = _cloudinary.Upload(uploadParams);
            }
        }

        photoDto.Url = uploadResult.Uri.ToString();
        photoDto.PublicId = uploadResult.PublicId;

        var photo = _mapper.Map<Photo>(photoDto);

        photo.User = user;

        if (!user.Photos.Any(m => m.IsMain))
            photo.IsMain = true;

        user.Photos.Add(photo);



        if (await _repo.SaveAll())
        {
            var photoToReturn = _mapper.Map<PhotoForReturnDto>(photo);
            return CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn);
        }

        return BadRequest("Could not add the photo");
    }
}

这是 postman 的错误:

我尝试使用 [FromBody] 但它也没有用。 我会 appriciate 任何帮助。

当通过 Postman 提交文件时,确保不要自行填写 Content-Type header。 Postman 会自动将其设置为 multipart/form-data 值。

Content-Type header 设置为 application/json 会阻止 ASP.Net Core 正确处理请求数据。所以IFormFile属性没有填,设置为null.