简体   繁体   中英

.net core Web API - 415 Unsupported Media Type

I'm building a .net core WebApi while following a course. I'm trying to upload photos, but I keep getting the error

415 - Unsupported file type

Here is the relevant controller

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

I have no idea what the error is? Any ideas?

Response and Request Headers

Your c# code sends a HTTP POST request under the hood. This request has a Content-Type header. You get a 415 if the Content-Type does not match the actual content type of the body of your POST request.

Try attaching a Content-Type header with the appropriate type. For a list of possible type values, see What are all the possible values for HTTP "Content-Type" header?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM