I have been attempting to send an xls or any other file from my angular application to a .NET core controller, but none of my methods seem to work...
Below is my component where I call my service upon button click:
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 {
}
});
}
Here is the service method used:
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);
}
And here is the controller implementation:
[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;//.....
}
}
However, the request does not seem to be reaching the endpoint. The error message displayed is
POST http://localhost:44328/api/Student net::ERR_CONNECTION_RESET
In the startup.cs file, cors has been added and everything appears to be configured correctly. I am at a loss as to what could be wrong...
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();
}
I'm in need of fresh ideas on how to solve this issue after spending so much time on it.