簡體   English   中英

從 ASP.NET CORE Web Api 獲取 React 中的特定響應標頭(例如,Content-Disposition)

[英]Get a specific response header (e.g., Content-Disposition) in React from an ASP.NET CORE Web Api

我正在從WebAPI控制器返回一個文件。 Content-Disposition標頭值會自動填充,它還包含我的文件名。

我的后端代碼如下所示:

[HttpGet("Download")]
public async Task<ActionResult> Download([FromQuery]CompanySearchObject req)
{
    string fileName = "SomeFileName_" + DateTime.UtcNow.Date.ToShortDateString() + ".csv";

    var result = await _myService.GetData(req);

    Stream stream = new System.IO.MemoryStream(result);

    return File(stream, "text/csv", fileName.ToString());
}

在我的前端:

exportData(params).then(response => {
      console.log(response);
      console.log('Response Headers:', response.headers);
      const type = response.headers['content-type'];
      const blob = new Blob([response.data], { type: type, encoding: 'UTF-8' });
      //const filename = response.headers['content-disposition'].split('"')[1];
      //alert(filename);
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = 'file.xlsx';
      link.click();
      link.remove();
   });
};

在此處輸入圖片說明

但是我正在努力獲取這些數據,因為當我在前端執行 console.log 時,我看不到這個......正如你所看到的,我記錄了響應console.log('Response Headers:', response.headers); 但我唯一看到的是:

在此處輸入圖片說明

這個數據不應該在某個地方嗎? 我想知道如何從Content-Disposition讀取值並獲取文件名?

謝謝大家干杯

有同樣的問題。 我的問題是 CORS。 如果你正在使用它,你需要在你的配置中像這樣公開它:

app.UseCors(builder =>
            {
                builder.AllowAnyOrigin();
                builder.AllowAnyMethod();
                builder.AllowAnyHeader();
                builder.WithExposedHeaders("Content-Disposition"); // this is the important line
            });

我這樣做的方法是遍歷所有請求標頭,直到匹配我正在尋找的特定標頭。

// Headers
private void GetSetCustomHeaders(ref string theUsername, ref string thePassword, ref string theAPIKey)
{
    try
    {
        foreach (KeyValuePair<string, IEnumerable<string>> header in this.Request.Headers)
        {
            string headerType = header.Key;
            string headerTypeUpperTrim = headerType.Trim().ToUpper();
            IEnumerable<string> headerValue = header.Value;
            string fullHeaderValue = "";
            bool isFirstHeaderValue = true;
            foreach (string headerValuePart in headerValue)
            {
                if (isFirstHeaderValue)
                {
                    fullHeaderValue = headerValuePart;
                    isFirstHeaderValue = false;
                }
                else
                {
                    fullHeaderValue = fullHeaderValue + Environment.NewLine + headerValuePart;
                }
            }
            if (headerTypeUpperTrim == "USERNAME")
            {
                theUsername = fullHeaderValue;
            }
            else if (headerTypeUpperTrim == "PASSWORD")
            {
                thePassword = fullHeaderValue;
            }
            else if (headerTypeUpperTrim == "APIKEY")
            {
                theAPIKey = fullHeaderValue;
            }
        }
    }
    catch (Exception)
    {
        //MessageBox.Show("Error at 'GetSetCustomHeaders'" + Environment.NewLine + Environment.NewLine + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }
}

在上面的示例代碼中,我正在尋找“用戶名”、“密碼”和“APIKey”。 它們作為ref參數傳遞,因此如果它們在此方法中設置,它們也會在調用此GetSetCustomHeaders方法的方法中設置,因為它引用相同的內容。 所以當我最初調用這個方法時,我的變量被設置為string.Empty

希望這是有幫助的。

對於 Fetch Response Headers,它返回的是一個可迭代對象,你必須遍歷response.headers而不是log response.headers object

試試下面的代碼:

response.headers.forEach(console.log);
console.log(response.headers.get('content-disposition'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM