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

非常感谢。

负数

通过CORS策略已阻止从源地址“ http:// localhost:4200访问“ http:// localhost:5000 / api / upload处的XMLHttpRequest 要求的资源。

实际上,我怀疑在配置.NET后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>

附带说明,不要在操作方法内将a返回nullIActionResult它将导致未处理的异常:

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Angular / ASP.NET Core 2.1 CORS 问题

来自分类Dev

CORS和ASP.Net Web API

来自分类Dev

Asp.Net Core允许CORS中的IP范围

来自分类Dev

放置请求期间的 ASP Net Core CORS 错误

来自分类Dev

部署angular 8和asp.net core 3.1的步骤

来自分类Dev

ASP.net Core中的加密和Angular中的解密

来自分类Dev

Auth0、Angular 4 和 ASP.NET Core

来自分类Dev

ASP.NET中的CORS问题

来自分类Dev

如何为ASP.NET允许CORS

来自分类Dev

ASP.NET Core Swagger无法在Chrome中出现CORS错误

来自分类Dev

无法在ASP.NET Core 1.0中启用跨域请求(CORS)

来自分类Dev

如何在ASP.NET Core MVC中启用跨域请求(CORS)

来自分类Dev

在ASP.Net 5 / Core中启用跨域资源共享(CORS)

来自分类Dev

如何在ASP.NET Core 2.2项目中为子域正确启用CORS?

来自分类Dev

如何在ASP.NET Core 3.1中为每种请求启用Cors

来自分类Dev

在ASP.NET Core 3.1中为多个环境处理CORS策略

来自分类Dev

尽管正确设置,但 ASP.NET Core 2 中的 CORS 不起作用

来自分类Dev

Angular POST和.NET Core WEB Api-401未经授权的错误/ CORS

来自分类Dev

使用.NET Core和Angular Client,即使在启用后,CORS错误仍会继续发生

来自分类Dev

.net core 2.1 CORS API

来自分类Dev

使用signalR和ASP.NET MVC 3的CORS的异常行为

来自分类Dev

使用signalR和ASP.NET MVC 3的CORS的异常行为

来自分类Dev

我是否必须分别使用Angular 7和Asp.net发布对象?

来自分类Dev

ASP.NET CORE 2.2.0 / Angular 8 / signalr1.0.0阻止对XMLHttpRequest的访问[[CORS Policy-Access-Control-Allow-Origin)失败]

来自分类Dev

在 Angular7 ASP .Net Core 2.1 中使用 ng2-file-upload 视频上传失败

来自分类Dev

SignalR:通知从 ASP.NET Core Web API 到 Angular 7 客户端的冗长操作的进度

来自分类Dev

asp .net 和 asp .net core 有什么区别?

来自分类Dev

如何在asp.net core和ef7中的并行方法中使用注入的DbContext?

来自分类Dev

即使允许几乎所有内容,ASP.NET 5 / Core / vNext CORS也无法正常工作

Related 相关文章

  1. 1

    Angular / ASP.NET Core 2.1 CORS 问题

  2. 2

    CORS和ASP.Net Web API

  3. 3

    Asp.Net Core允许CORS中的IP范围

  4. 4

    放置请求期间的 ASP Net Core CORS 错误

  5. 5

    部署angular 8和asp.net core 3.1的步骤

  6. 6

    ASP.net Core中的加密和Angular中的解密

  7. 7

    Auth0、Angular 4 和 ASP.NET Core

  8. 8

    ASP.NET中的CORS问题

  9. 9

    如何为ASP.NET允许CORS

  10. 10

    ASP.NET Core Swagger无法在Chrome中出现CORS错误

  11. 11

    无法在ASP.NET Core 1.0中启用跨域请求(CORS)

  12. 12

    如何在ASP.NET Core MVC中启用跨域请求(CORS)

  13. 13

    在ASP.Net 5 / Core中启用跨域资源共享(CORS)

  14. 14

    如何在ASP.NET Core 2.2项目中为子域正确启用CORS?

  15. 15

    如何在ASP.NET Core 3.1中为每种请求启用Cors

  16. 16

    在ASP.NET Core 3.1中为多个环境处理CORS策略

  17. 17

    尽管正确设置,但 ASP.NET Core 2 中的 CORS 不起作用

  18. 18

    Angular POST和.NET Core WEB Api-401未经授权的错误/ CORS

  19. 19

    使用.NET Core和Angular Client,即使在启用后,CORS错误仍会继续发生

  20. 20

    .net core 2.1 CORS API

  21. 21

    使用signalR和ASP.NET MVC 3的CORS的异常行为

  22. 22

    使用signalR和ASP.NET MVC 3的CORS的异常行为

  23. 23

    我是否必须分别使用Angular 7和Asp.net发布对象?

  24. 24

    ASP.NET CORE 2.2.0 / Angular 8 / signalr1.0.0阻止对XMLHttpRequest的访问[[CORS Policy-Access-Control-Allow-Origin)失败]

  25. 25

    在 Angular7 ASP .Net Core 2.1 中使用 ng2-file-upload 视频上传失败

  26. 26

    SignalR:通知从 ASP.NET Core Web API 到 Angular 7 客户端的冗长操作的进度

  27. 27

    asp .net 和 asp .net core 有什么区别?

  28. 28

    如何在asp.net core和ef7中的并行方法中使用注入的DbContext?

  29. 29

    即使允许几乎所有内容,ASP.NET 5 / Core / vNext CORS也无法正常工作

热门标签

归档