首页 > 解决方案 > 从.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' 标头存在于请求的资源上。

谢谢

标签: angularhttpasp.net-web-apicors

解决方案


看来您应该在 asp.net 应用程序中启用CORS。这是服务器端错误。

在 Visual Studio 中,从工具菜单中选择 NuGet 包管理器,然后选择包管理器控制台。在包管理器控制台窗口中,键入以下命令:

Install-Package Microsoft.AspNet.WebApi.Cors

有关如何在 Web API 中启用 CORS 的更多信息,请参阅以下链接:

在 ASP.NET Web API 2 中启用跨域请求


推荐阅读