angular - 从.net mvc api控制器下载角度应用程序中的文件时被CORS策略错误阻止
问题描述
我正在尝试从 angular 8 应用程序从 asp.net web api 下载文件并收到 CORS 错误。我的 web api 的所有控制器都启用了 CORS。如果我不返回流,那么它工作正常,当 api 返回流时开始抛出 CORS 错误。
API代码:-
var stream = new MemoryStream(pck.GetAsByteArray());
stream.Flush();
stream.Position = 0;
response.ClearContent();
response.Clear();
response.Buffer = true;
response.Charset = "";
response.Cache.SetCacheability(HttpCacheability.NoCache);
response.AddHeader("content-disposition", "attachment; filename=" + filename);
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
stream.Close();
response.BinaryWrite(data);
response.Flush();
response.End();
角码:-
let options = new RequestOptions({responseType: ResponseContentType.Blob, headers });
this.http.get(url,{ observe: 'response', responseType: 'blob'} ).subscribe((response)=>{
const blob = new Blob([response.body],
{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const file = new File([blob], 'reports.xlxs',
{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(file);
});
一旦调用订阅,我就会开始低于错误。当我调试它执行所有api代码并返回以下错误。
错误:-从源“ http://localhost:4200 ”访问“ http://localhost:19119//offers/42428/export/orderDetails ”处的 XMLHttpRequest已被 CORS 策略阻止:没有“访问控制允许” -Origin' 标头存在于请求的资源上。
谢谢
解决方案
看来您应该在 asp.net 应用程序中启用CORS。这是服务器端错误。
在 Visual Studio 中,从工具菜单中选择 NuGet 包管理器,然后选择包管理器控制台。在包管理器控制台窗口中,键入以下命令:
Install-Package Microsoft.AspNet.WebApi.Cors
有关如何在 Web API 中启用 CORS 的更多信息,请参阅以下链接:
推荐阅读
- postgresql - Postgres - 创建可以存在于多个模式中的触发器
- php - 后端日志:PHP 注意:试图获取非对象的属性
- python - 如何在 Python 中从图像中读取文本的颜色
- android - 我可以在 AWS 中设置 iOS 和 android 版本吗?
- php - EasyRDF 示例在服务器上不适合我
- javascript - 处理中的图像圆失真 / p5js
- html - HTML/CSS:创建两行,分别为 2 和 3 列,它们应该占据窗口视口并且单元格应该滚动
- variables - Applescript 对列表中的每个项目重复命令。每行作为变量添加到命令
- android - 无法在 Firebase Firestore 中存储下载 URL
- java - Json 方法预期的表达式