【发布时间】:2019-08-22 04:04:28
【问题描述】:
为什么我收到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 中的代码正常工作
下面是上传控制器代码
[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 没有发送数据吗?
非常感谢。
【问题讨论】:
-
您要上传文件吗?如果是这样,它应该是一个帖子而不是一个获取。通常你应该检查是否有任何文件上传,但如果列表中有多个文件,你也应该处理。 mircosoft 文档中有一个简单的示例:docs.microsoft.com/de-de/aspnet/core/mvc/models/…
-
有关在 ASP.NET Core 中使用 cors 的信息:stackoverflow.com/questions/31942037/…
标签: angular asp.net-web-api asp.net-core file-upload