I work on asp.net core application 2.2 I face issue when download file from server path as below
DeliverySystem:1 Access to XMLHttpRequest at 'https://pno.mydataz.com:7072/api/DeliverySys/Download?fileName=DeliveryGeneration_Input.xlsx' from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
what I try is :
[HttpGet]
[Route("Download")]
public IActionResult Download(string filename)
{
if (filename == null)
return Content("filename not present");
var path = Path.Combine(
GetFilesDownload, filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
stream.CopyTo(memory);
}
memory.Position = 0;
return File(memory, "text/plain", Path.GetFileName(path));
}
I Get error when download static excel file from server so why this error display and how to solve issue ?
updated Post
I set core policy on my start up application
app.UseCors("CorsPolicy");
app.UseCors(builder =>
builder.WithOrigins(Configuration["ApplicationSettings:Client_URL"].ToString())
.AllowAnyHeader()
.AllowAnyMethod()
);
app.UseAuthentication();
front end is angular 8 as below :
DownloadFile(filePath: string, fileType: string): Observable<any> {
let fileExtension = fileType;
let input = filePath;
return this.http.get(this.url +'DeliverySys/Download'+ "?fileName=" + input, {
responseType: 'blob',
observe: 'response'
})
.pipe(
map((res: any) => {
return new Blob([res.body], { type: fileExtension });
})
);
}
link generated as below :
https://pn.mydataz.com:7072/api/DeliverySys/Download?fileName=DeliveryGeneration_Input.xlsx
and this link not on
current client_url on app settings not
https://pno.mydataz.com:7072/
current client url on app settings is
"Client_URL": "http://localhost:4200"
request header is :
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en,ar;q=0.9,en-US;q=0.8
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ
Connection: keep-alive
Host: pn.mydataz.com:7072
Origin: https://pno.mydataz.com:7071
Referer: https://pno.mydataz.com:7071/
Pls allow me to post my test information here to show more details well.
First this is my controller and file structure, and when I call the link
https://localhost:44395/downloadin the browser, it can pop up the download window.and here I set the CORS policy in my startup file like this:
And I create a SPA with an ajax call to this url, this function :
And My test result: