繁体   English   中英

错误访问 XMLHttpRequest at file from origin has been blocked by CORS policy

[英]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));
}

从服务器下载 static excel 文件时出现错误,为什么显示此错误以及如何解决问题?

更新后的帖子

我为我的启动应用程序设置了核心策略

 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 });
          })
      );
}

链接生成如下:

https://pn.mydataz.com:7072/api/DeliverySys/Download?fileName=DeliveryGeneration_Input.xlsx

这个链接不在

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/

请允许我在这里发布我的测试信息,以便更好地展示更多细节。

首先这是我的controller和文件结构,当我在浏览器中调用链接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:

  $(function() {
        initPage7();
  });
  function initPage7() {
    $.ajax({
        url: "https://localhost:44395/download",
        type: 'get',
        success: function(data) {}
    })
  }

我的测试结果:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM