【发布时间】:2021-10-20 17:24:27
【问题描述】:
我在 asp.net 核心应用程序 2.2 上工作,当从以下服务器路径下载文件时遇到问题
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.
我尝试的是:
[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));
}
从服务器下载静态 excel 文件时出现错误 那么为什么会显示此错误以及如何解决问题?
更新帖子
我在启动应用程序上设置核心策略
app.UseCors("CorsPolicy");
app.UseCors(builder =>
builder.WithOrigins(Configuration["ApplicationSettings:Client_URL"].ToString())
.AllowAnyHeader()
.AllowAnyMethod()
);
app.UseAuthentication();
前端为 8 角,如下所示:
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 });
})
);
}
链接生成如下:
https://pn.mydataz.com:7072/api/DeliverySys/Download?fileName=DeliveryGeneration_Input.xlsx
这个链接不在
current client_url on app settings not
https://pno.mydataz.com:7072/
current client url on app settings is
"Client_URL": "http://localhost:4200"
请求头是:
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/
【问题讨论】:
-
您是否在 startup.cs 中设置了 cors 策略,例如 this?
-
你的计划是什么?您是否在另一个项目中发送了请求?我的意思是它不应该在同一个程序中出现 cors 错误。
-
是的,我制定了核心政策
-
1) 我认为你不应该给
app.UseCors()打两次电话。 2)你在ApplicationSettings:Client_URL中配置了什么值? -
@ahmedbarbary 使用
builder.AllowAnyOrigin()来排除错误Origin 的可能性怎么样?
标签: c# asp.net-core asp.net-core-webapi asp.net-core-2.2