簡體   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