angular - 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 没有发送数据吗?
非常感谢。
解决方案
从源“ 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)
{
// ...
}
}
推荐阅读
- javascript - JavaScript如何基于数组调用函数的函数等?
- mysql - 如何修复“添加外键约束失败。在引用的表‘account’中缺少约束‘transactions_ibfk_1’的索引”
- c# - 如何从 Azure Key Vault 获取 VaultProperties.NetworkAcls 属性
- tensorflow - 在tensorflow中为cifar10寻找resnet的训练脚本
- azure - 使用 SOAP UI 进行调试
- pyspark - PySpark when/otherwise 多个条件
- java - 如何在运行时实现“可重绘”ListView?
- javascript - Javascript按时间更改句子
- html - 在 Ruby 中使用 Nogokiri 解析 HTML
- r - 在循环中使用 Display() 和 as_image() 将图像添加到 flextable 不起作用