我有PhotosController
课程的帖子请求。当我测试这段代码时,它总是返回一个空值。我没有看到文件详细信息。
基本上它会得到userid
和PhotoDto
,它应该返回照片。我使用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");
}
}
这是邮递员的错误:
答案 0 :(得分:2)
从邮递员提交文件时,请确保您没有自己填写Content-Type
标题。邮差会自动将其设置为multipart/form-data
值。
将Content-Type
标头设置为application/json
会阻止ASP.Net Core正确处理请求数据。这就是IFormFile
属性未填充且设置为null
的原因。