我正在尝试从 angular 8 应用程序从 Web API 下载文件 asp.net 并收到 CORS 错误。CORS 已为我的 Web API 的所有控制器启用。如果我不返回流,那么它可以正常工作,当 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 的所有代码并返回以下错误。
错误:- CORS策略阻止了从源"http://localhost:4200"访问"http://localhost:19119//offers/42428/export/orderDetails"处的XMLHttpRequest:请求的资源上不存在"访问控制允许源"标头。
谢谢
似乎您应该在 asp.net 应用程序中启用CORS。这是服务器端错误。
在 Visual Studio 中,从"工具"菜单中选择"NuGet 包管理器",然后选择"包管理器控制台"。在"程序包管理器控制台"窗口中,键入以下命令:
Install-Package Microsoft.AspNet.WebApi.Cors
有关如何在 Web API 中启用 CORS 的详细信息,请参阅以下链接:
在 Web API 2 ASP.NET 启用跨源请求
将以下代码行添加到 HttpResponse 解决了我的问题。
response.AddHeader("Access-Control-Allow-Origin", "*");