【发布时间】:2019-02-23 01:37:09
【问题描述】:
我一直在尝试将 xls(或任何其他)文件从我的 Angular 应用程序发送到 .NET 核心控制器。我试了很多方法,都没有奏效...
这是我的组件,单击按钮时我会调用我的服务:
handleFileInput(file: FileList) {
this.fileToUpload = file.item(0);
const url = 'http://localhost:44328/api/Student';
this.studentService.postFile(this.url, this.fileToUpload)
.subscribe((res: any) => {
},
(err) => {
if (err.status === 401) {
} else {
}
});
}
服务方法如下:
postFile(url: string, fileToUpload: File): Observable<Response> {
const formData: FormData = new FormData();
formData.append('File', fileToUpload, fileToUpload.name);
const headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
const options = new RequestOptions({ headers });
return this.http.post(url, formData, options);
}
这是我的控制器:
[Route("/api/[controller]")]
public class StudentController : Controller
{
private readonly IStudentsService _service;
public StudentController(IStudentsService service)
{
_service = service;
}
[HttpPost, DisableRequestSizeLimit]
public ActionResult UploadFile()
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var httpRequest = HttpContext.Request.Form;//.....
}
}
但请求永远不会到来......我得到POST http://localhost:44328/api/Student net::ERR_CONNECTION_RESET
在我的 startup.cs 类中,我添加了 cors,一切似乎都是正确的,我真的不明白这里出了什么问题..
startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(x => x.AddProfile(new MappingsProfile()));
services.AddDbContext<museumContext>(options =>
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
});
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAllOrigins"));
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder =>
builder.WithOrigins("http://localhost:44328")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
app.UseAuthentication();
app.UseCors("AllowAllOrigins");
app.UseMvc();
}
这里有什么问题?我真的没有想法,也许在花了这么多时间后我需要重新思考一下
【问题讨论】:
-
我建议尝试一个实用程序,独立于您现在/已经测试过的内容。在测试两个未知数之前尝试使用 postman 之类的方法,看看您的服务是否真的有效...... :)
标签: c# asp.net angular typescript asp.net-core