.net核心Web API-415不支持的媒体类型

时间:2019-03-06 17:09:38

标签: c# .net-core

在学习课程的同时,我正在构建.net核心WebApi。我正在尝试上传照片,但是不断出现错误

  

415-不支持的文件类型

这是相关的控制者

[HttpPost]
public async Task<IActionResult> AddPhotoForUser(int userId, [FromForm] PhotoForCreationDto photoForCreationDTO)
{
    if(userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
        return Unauthorized();

    var userFromRepo = await _repo.GetUser(userId);

    var file = photoForCreationDTO.File;

    var uploadResult = new ImageUploadResult();

    if(file.Length > 0)
    {
        using(var stream = file.OpenReadStream())
        {
            var uploadParams = new ImageUploadParams()
            {
                File = new FileDescription(file.Name, stream),
                Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
            };

            uploadResult = _cloudinary.Upload(uploadParams);
        }
    }

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

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

    if(!userFromRepo.Photos.Any(u => u.IsMain))
        photo.IsMain = true;

    userFromRepo.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");
}   

我不知道错误是什么?有什么想法吗?

Response and Request Headers

1 个答案:

答案 0 :(得分:0)

您的c#代码在后台发送HTTP POST请求。该请求具有Content-Type标头。如果Content-Type与POST请求正文的实际内容类型不匹配,则会得到415。

尝试附加具有适当类型的Content-Type标头。有关可能的类型值的列表,请参见What are all the possible values for HTTP "Content-Type" header?