WebAPI 核心 IFormFile 始终显示为空

lam*_*bda 5 c# asp.net-web-api asp.net-core angular

我有一个 angular 4 的前端,一个 ASP.NET Core WebAPI 的后端,它们的功能是,将数据和一个人的简历发送到一个 SQL Server 数据库,但是......总是捕获数据并将文件发送到数据库的方法的 IFormFile 为空。

我已经尝试了在互联网上找到的所有类型的解决方案,但没有一个对我有用。

作为 Post 方法的响应,我收到此异常

An unhandled exception occurred while processing the request.  
  NullReferenceException: Object reference not set to an instance of an object.  
  WebApplication.Controllers.CandidateController+<Post>d__4.MoveNext() in CandidateController.cs, line 60
Run Code Online (Sandbox Code Playgroud)

在这里,我粘贴了执行此操作的项目的部分代码。

完整代码的github链接:
前端代码
后端代码

HTML

<form class="col-md-6 offset-md-3" method="POST" enctype="multipart/form-data" #form="ngForm" (ngSubmit)="onSubmit(form)">
  <div class="form-group row">
    <label for="name" class="col-sm-2 col-form-label">Name</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" placeholder="Nome completo" id="name"  name="name" ngModel />
    </div>
  </div>
  <div class="form-group row">
    <label for="email" class="col-sm-2 col-form-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" id="email" placeholder="Email" name="email" ngModel />
      <small id="emailHelp" class="form-text text-muted">
        We'll never share your email with anyone else.
      </small>
    </div>
  </div>
  <div class="form-group row">
    <label for="country" class="col-sm-2 col-form-label">Country</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="country" placeholder="Country" name="country" ngModel />
    </div>
  </div>
  <div class="form-group row">
    <label for="state" class="col-sm-2 col-form-label">State</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="state" placeholder="Estado" name="state" ngModel />
    </div>
  </div>
  <div class="form-group row">
    <label for="city" class="col-sm-2 col-form-label">City</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="city" placeholder="Cidade" name="city" ngModel />
    </div>
  </div>
  <div class="form-group row">
    <label for="file" class="col-sm-2 col-form-label">Curriculum</label>
    <div class="col-sm-10">
        <input type="file" id="file" name="file" ngModel />
    </div>
  </div>
  <div class="container text-center">
    <button type="submit" class="btn btn-outline-dark">Submit</button>
  </div>
</form>
Run Code Online (Sandbox Code Playgroud)

角 4

onSubmit(form: NgForm) {
  const { file } = form.value;
  delete form.value.file;

  var data = new FormData();
  data.append('Candidates', JSON.stringify(form.value));
  data.append('file', file);

  console.log(form.value);
  console.log(file);

  const headers = new Headers();
  headers.append('Access-Control-Allow-Origin', '*');

  const options = new RequestOptions({headers: headers});

  this.http.post("http://localhost:54392/api/candidates", data, options)
    .subscribe(
      data => {
        console.log("Foi");
      },
      error => {
        console.log("Não foi");
      });
}
Run Code Online (Sandbox Code Playgroud)

C#

[HttpPost("candidates")]
public async Task<IActionResult> Post(IFormFile file)
{
    var json = HttpContext.Request.Form["Candidates"];      
    var jsonTextReader = new JsonTextReader(new StringReader(json));
    var candidate = new JsonSerializer().Deserialize<Candidate>(jsonTextReader);

    if (!ModelState.IsValid) 
        return BadRequest();

    using (var memoryStream = new MemoryStream())
    {
        await file.OpenReadStream().CopyToAsync(memoryStream);
        candidate.CurriculumVitae = memoryStream.ToArray();
    }
    await dataBase.AddAsync(candidate);
    dataBase.SaveChanges();
    return Ok(candidate);
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*kin 3

在没有插件的情况下在 Angular 4 中上传图像提供了您尝试实现的过程的演练。它用于@ViewChild获取对 DOM 中文件输入的引用,然后在构建FormData. 在您的场景中,这涉及一些更改,如下所示:

  1. ngModel将 HTML 中的文件输入替换为#file. 这将创建一个模板引用变量@ViewChild,在下一步使用时可以在组件内部访问该变量。
  2. 添加@ViewChild('file') fileInput;到构造函数上方的组件。这会将#file模板引用变量链接到您的组件代码。
  3. 从您的组件中删除以下代码:

    const { file } = form.value;
    delete form.value.file;
    
    Run Code Online (Sandbox Code Playgroud)

    file此时该属性将不再存在,因此无需删除任何内容。

  4. 替换data.append('file', file);为以下内容:

    let fileBrowser = this.fileInput.nativeElement;
    if (fileBrowser.files && fileBrowser.files[0]) {
        data.append("file", fileBrowser.files[0]);
    }
    
    Run Code Online (Sandbox Code Playgroud)

    最后的代码块获取文件的句柄并将其附加到您的FormData.

您可以根据需要命名变量和模板引用变量。唯一需要具体说明的是,file中使用的字符串值data.append 必须与 C# 变量使用的变量名称相匹配IFormFile

顺便说一句,您还可以删除自定义设置Headers,因为请求标头的RequestOptions设置在这里不执行任何操作。Access-Control-Allow-Origin该标头应由服务器在响应上设置。