为什么即时收录Cors Error

Access to XMLHttpRequest at 'http://localhost:5000/api/upload' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.


据我所理解。在我的asp.net core web api启动类中启用了cors

这是我的代码

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseCors(x => x.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

        app.UseAuthentication();
        app.UseMvc();
}


这是我的Angular 7代码

fileupload的html

<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
  <div class="form-group">
      <input type="file" name="image"  />
  </div>
  <div class="form-group">
      <button class="btn btn-primary">Submit</button>
  </div>
</form>


这是fileupload.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-fileupload',
  templateUrl: './fileupload.component.html',
  styleUrls: ['./fileupload.component.css']
})
export class FileuploadComponent implements OnInit {
  fileData: File = null;
  formGroup = new FormGroup({
    one: new FormControl
  });
  constructor(private http: HttpClient) { }

  fileProgress(fileInput: any) {
    this.fileData = <File>fileInput.target.files[0];
  }

  ngOnInit() {
  }

  onSubmit() {
    const formData = new FormData();
    formData.append('file', this.fileData);
    this.http.post('http://localhost:5000/api/upload', formData)
    .subscribe(res => {
      console.log(res);
      alert('SUCCESS !!');
    })

    console.log('Called');
  }

}


实际上,我正在按照本教程进行操作:

https://www.tutsmake.com/new-angular-7-upload-file-image-example/


我在Angular 7的帮助下检查文件上传api的部分。我使用邮递员测试了API,到目前为止,它与api中的代码都能正常工作

angular - Asp.net Core和Angular 7 Cors-LMLPHP

以下是上传控制器代码

[Produces("application/json")]
    [Route("api/[controller]")]
    public class UploadController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {

            try
            {
                var file = Request.Form.Files[0];
                Console.WriteLine();

                return null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                throw ex;
            }
        }
    }


我也收到错误

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.' on

var file = Request.Form.Files[0];


这是因为Angular 7没有发送数据吗?

非常感谢。

最佳答案

CORS策略已阻止从源“ http://localhost:5000/api/upload”访问“ http://localhost:4200”处的XMLHttpRequest:请求的资源上不存在“ Access-Control-Allow-Origin”标头。


实际上,我怀疑配置CORS后是否忘记了重新启动ASP.NET Core Server。

假设您使用的是默认模板,那么您现有的代码对我来说效果很好。
如果仍然无法实现,则可以粘贴Startup类的完整代码。


我也收到错误

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.' on

var file = Request.Form.Files[0];


这是因为Angular 7没有发送数据吗?


是。这是因为在选择文件时,您没有绑定事件处理程序来设置fileData属性。

要解决此问题,请创建onFileChange(event)方法:

@Component({
  selector: 'app-fileupload',
  templateUrl: './fileupload.component.html',
  styleUrls: ['./fileupload.component.css']
})
export class FileuploadComponent implements OnInit {

  // ...

  onFileChange(event){
    this.fileData = <File> event.target.files[0];
  }

  // ...
}


并如下更改模板:

<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
  <div class="form-group">
      <input type="file" name="image" (change)="onFileChange($event)"  />
  </div>
  <div class="form-group">
      <button class="btn btn-primary">Submit</button>
  </div>
</form>




另外请注意,请勿在操作方法内将null作为IActionResult返回。它将导致未处理的异常:

    public IActionResult Index()
    {
        try
        {
            var file = Request.Form.Files[0];
            Console.WriteLine();

            return null;             ////////// don't return null
        }
        catch (Exception ex)
        {
            // ...
        }
    }

09-18 00:40