简体   繁体   中英

Asp.net Core and Angular 7 Cors

Why do im receving the 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.

As far as i understand. The cors is enabled in my startup class in my asp.net core web api

And here is my code

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();
}

And this is my Angular 7 Code

The html for 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>

And this is the 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');
  }

}

Actually im following this tutorial:

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

And im in the part where i am checking the file upload api with the help of the Angular 7. I tested the API using postman and it worked correctly with the code in the api so far

在此处输入图片说明

And below is the Upload controller code

[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;
            }
        }
    }

I'm also receving an error

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]; 

is this because of the Angular 7 is not sending data?

Thank you so much.

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.

Actually, I doubt whether you forgot to restart the ASP.NET Core Server after you configure the CORS .

Assuming you're using the default template, your existing code works fine for me. If you still cannot make it, you could paste the complete code of your Startup class.

I'm also receving an error

 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]; 

is this because of the Angular 7 is not sending data?

Yes. That's because you haven't binded an event handler to set the fileData property when selecting a file .

To fix it, create a method of 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];
  }

  // ...
}

and change your template as below:

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

As a side note, don't return a null as an IActionResult within your action method. It will result in an unhandled exception:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM