CORS 策略阻止了从源文件访问 XMLHttpRequest 的错误
error Access to XMLHttpRequest at file from origin has been blocked by CORS policy
我在 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 文件时出错
那么为什么显示此错误以及如何解决问题?
已更新Post
我在我的启动应用程序中设置了核心策略
app.UseCors("CorsPolicy");
app.UseCors(builder =>
builder.WithOrigins(Configuration["ApplicationSettings:Client_URL"].ToString())
.AllowAnyHeader()
.AllowAnyMethod()
);
app.UseAuthentication();
前端是 angular 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 });
})
);
}
link 生成如下:
https://pn.mydataz.com:7072/api/DeliverySys/Download?fileName=DeliveryGeneration_Input.xlsx
这个link不在
current client_url on app settings not
https://pno.mydataz.com:7072/
current client url on app settings is
"Client_URL": "http://localhost:4200"
请求 header 是:
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/
请允许我post我的测试信息在这里显示更多细节。
首先这是我的控制器和文件结构,当我在浏览器中调用link https://localhost:44395/download
时,它可以弹出下载window。
在这里,我在我的启动文件中设置了 CORS 策略,如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
然后我创建了一个 SPA,其中 ajax 调用了这个 url,这个函数:
$(function() {
initPage7();
});
function initPage7() {
$.ajax({
url: "https://localhost:44395/download",
type: 'get',
success: function(data) {}
})
}
我的测试结果:
我在 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 文件时出错 那么为什么显示此错误以及如何解决问题?
已更新Post
我在我的启动应用程序中设置了核心策略
app.UseCors("CorsPolicy");
app.UseCors(builder =>
builder.WithOrigins(Configuration["ApplicationSettings:Client_URL"].ToString())
.AllowAnyHeader()
.AllowAnyMethod()
);
app.UseAuthentication();
前端是 angular 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 });
})
);
}
link 生成如下:
https://pn.mydataz.com:7072/api/DeliverySys/Download?fileName=DeliveryGeneration_Input.xlsx
这个link不在
current client_url on app settings not
https://pno.mydataz.com:7072/
current client url on app settings is
"Client_URL": "http://localhost:4200"
请求 header 是:
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/
请允许我post我的测试信息在这里显示更多细节。
首先这是我的控制器和文件结构,当我在浏览器中调用link https://localhost:44395/download
时,它可以弹出下载window。
在这里,我在我的启动文件中设置了 CORS 策略,如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
然后我创建了一个 SPA,其中 ajax 调用了这个 url,这个函数:
$(function() {
initPage7();
});
function initPage7() {
$.ajax({
url: "https://localhost:44395/download",
type: 'get',
success: function(data) {}
})
}
我的测试结果: