当我想保存图像时,我遇到了问题,我在模型中强制出现了错误,但是在应用程序运行时我没有收到任何错误行,当我使用断点时,我看到图像出现了直到模型有效,但有效返回错误,但我找不到解决方案,你能帮忙吗?
我在“创建”页面上获取图像数据的字段
<div class="form-group my-3">
<label asp-for="UniversityImage"></label>
<input name="file" type="file" class="form-control" />
</div>
我的管理仪表板
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([FromForm] UniversityDtoForInsertion universityDto, IFormFile file)
{
if (ModelState.IsValid)
{
string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", file.FileName);
await using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
universityDto.UniversityImage = String.Concat("/images/", file.FileName);
_serviceManager.UniversityService.CreateUniversity(universityDto);
TempData["success"] = $"{universityDto.UniversityName} has been created.";
return RedirectToAction("Index");
}
return View();
}
数据传输对象
public record UniversityDto
{
public int UniversityId { get; init; }
[Required(ErrorMessage = "UniversityName is Required")]
public string UniversityName { get; init; }
[Required(ErrorMessage = "UniversityDescription is Required")]
public string UniversityDescription { get; init; }
[Required(ErrorMessage = "UniversityAddress is Required")]
public string UniversityAddress { get; init; }
[Required(ErrorMessage = "UniversityWebAddress is Required")]
public string UniversityWebAddress { get; init; }
[Required(ErrorMessage = "UniversityPhone is Required")]
public string UniversityPhone { get; init; }
[Required(ErrorMessage = "UniversityImage is Required")]
public string UniversityImage { get; set; }
}
IUniversity服务层
University CreateUniversity(UniversityDtoForInsertion universityDto);
大学管理者层
public University CreateUniversity(UniversityDtoForInsertion universityDto)
{
if (universityDto is null)
{
throw new ArgumentNullException(nameof(universityDto));
}
University university = _mapper.Map<University>(universityDto);
_manager.University.Create(university);
_manager.Save();
return university;
}
IUniversityRepository层
public interface IUniversityRepository : IRepositoryBase<University>
{
IQueryable<University> GetAllUniversities(bool trackChanges);
University? GetOneUniversity(int id, bool trackChanges);
void CreateOneUni(University university);
void UpdateOneUni(University university);
void DeleteOneUni(University university);
}
大学存储库层
public void CreateOneUni(University university) => Create(university);
自从您通过
添加 UniversityImageuniversityDto.UniversityImage = String.Concat("/images/", 文件.文件名);
尝试在检查 ModelState.IsValid 之前添加它,例如:
universityDto.UniversityImage = String.Concat("/images/", file.FileName);
if (ModelState.IsValid)
{...}