SQL Server 正在尝试将包含IFormFile属性的模型从Angular 传递到asp.net核心Web API

4nkexdtk  于 2022-12-03  发布在  Angular
关注(0)|答案(1)|浏览(112)

我试图传递一个包含8个属性和IFormFile属性的模型。当我传递不包含文件的模型时,请求将正常或不正常,但当我将文件添加到模型并尝试发送它时,我收到一个内部服务器错误,描述为“错误:不支持接口类型的反序列化。类型“Microsoft.AspNetCore.Http. IFormFile”。路径:$. core图片|行号:0|行内字节位置:173号。“
Angular 14:
组件表:

userForm = this.fb.group({
    userName: ['', [ Validators.required, Validators.minLength(8), Validators.maxLength(24)]],
    email: ['', [ Validators.required, Validators.email]],
    phoneNumber: [''],
    passwordHash: ['', [ Validators.required, Validators.pattern('(?=.*[A-Za-z])(?=.*[0-9])(  ?=.*  [$@$!#^~%*?&,.<>"\'\\;:\{\\\}\\\[\\\]\\\|\\\+\\\-\\\=\\\_\\\)\\\(\\\)\\\`\\\/\\\\\\]])[A-Za-z0-9\d$@].{7,}'), 
    Validators.minLength(8), Validators.maxLength(16)]],
    firstName: ['', [ Validators.minLength(3), Validators.maxLength(24)]],
    lastName: ['', [ Validators.minLength(3), Validators.maxLength(24)]],
    gender: [true]
  }) as FormGroup;

  userFormSubmition(files: any){

    let fileToUpload = <File>files[0];
    const formData = new FormData();
    formData.append('file', fileToUpload, fileToUpload.name);
    this.userService.createUser(this.userForm.value).subscribe(response => {

维修

createUser(userCreation: UserCreation){
    return this.http.post(this.url + 'CreateUser', userCreation);
  }

Asp.net 6网络应用编程接口
型号

public class ApplicationUserCreationDto : ApplicationUserDto
    {
        [Required]
        public string UserName { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        public string PasswordHash { get; set; }
        public string PhoneNumber { get; set; }
        public IFormFile CorePhoto { get; set; }
    }

控制器方法

[HttpPost]
        [Route("CreateUser")]
        public async Task<IActionResult> CreateUser(ApplicationUserCreationDto userCreationDto)
        {
            if (ModelState.IsValid)
            {
                //upload photo
                var file = userCreationDto.CorePhoto;
                var folderName = Path.Combine("Resources", "Users/Images");
                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                if (file.Length > 0)
                {
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName;
                    var fullPath = Path.Combine(pathToSave, fileName.ToString());
                    var dbPath = Path.Combine(folderName, fileName.ToString());
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
                }
wgxvkvu9

wgxvkvu91#

欢迎您来到中国!
为了做到这一点,您需要有正确的API定义和UI请求。

  1. API应该如下所示(注意,我添加了[FromForm]属性
[ApiController]
[Route("[controller]")]
public class UploadController : Controller
{
    [HttpPost]
    [Route("CreateUser")]
    public async Task<IActionResult> CreateUser([FromForm]ApplicationUserCreationDto userCreationDto)
    {
        return Json(new
        {
            user = userCreationDto.UserName,
            fileName = userCreationDto.Photo.FileName
        });
    }
}

public class ApplicationUserCreationDto
{
    [Required]
    public string UserName { get; set; }

    public IFormFile Photo { get; set; }
}
  1. UI应发送一个Content-Type标头等于multipart/form-data值的请求,请在网络中检查它。代码可能如下所示
let formData = new FormData();

Object.keys(this.form.controls).forEach(formControlName => {
formData.append(formControlName,  this.form.get(formControlName).value);    
 });      
this.http.post('http://localhost:4200/api/trip',formData).subscribe(          
   (response) =>console.log(response),   
   (error) =>console.log(error)  
 )}

相关问题