首页 > 解决方案 > Asp.net Core 和 Angular 7 Cors

问题描述

为什么我收到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.

据我所理解。在我的启动课程中启用了 corsasp.net core web api

这是我的代码

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 代码

html 为fileupload

<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 中的代码正常工作

在此处输入图像描述

下面是上传控制器代码

[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 没有发送数据吗?

非常感谢。

标签: angularasp.net-web-apiasp.net-corefile-upload

解决方案


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

实际上,我怀疑您是否在配置CORS.

假设您使用的是默认模板,您现有的代码对我来说可以正常工作。如果您仍然无法做到,您可以粘贴您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>

附带说明一下,不要在您的操作方法中返回 anull作为 an 。IActionResult这将导致未处理的异常:

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

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

推荐阅读