
[英]MVC Web API Angular App ('http://localhost:4200' has been blocked by CORS policy)
[英]Blocked by CORS policy error when downloading file in angular app from .net mvc api controller
我正在尝试从 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 策略阻止:无“Access-Control-Allow” -Origin' 标头存在于所请求的资源上。
谢谢
看来您应该在 asp.net 应用程序中启用CORS 。 这是一个服务器端错误。
在 Visual Studio 中,从工具菜单中选择 NuGet 包管理器,然后选择包管理器控制台。 在包管理器控制台窗口中,键入以下命令:
Install-Package Microsoft.AspNet.WebApi.Cors
有关如何在 Web API 中启用 CORS 的更多信息,请参阅以下链接:
向 HttpResponse 添加以下代码行解决了我的问题。
response.AddHeader("Access-Control-Allow-Origin", "*");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.