javascript 在React中从ASP.NET CORE Web API获取特定响应标头(例如,Content-Disposition

6l7fqoea  于 2023-02-07  发布在  Java
关注(0)|答案(4)|浏览(166)

我正在从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中读取值并获得文件名?
谢谢伙计们干杯

0sgqnhkj

0sgqnhkj1#

有同样的问题。我的问题是CORS。如果你正在使用它,你需要在你的配置中这样暴露它:

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

ujv3wf0j2#

我这样做的方法是循环遍历所有的请求头,直到我匹配我正在寻找的特定头。

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

在上面的示例代码中,我正在查找'Username','Password'和'APIKey'。它们作为ref参数传递,因此如果在此方法中设置了它们,则在调用此GetSetCustomHeaders方法的方法中也会设置它们,因为它引用了相同的内容。因此,当我最初调用此方法时,我的变量设置为string.Empty
希望这是有帮助的。

2uluyalo

2uluyalo3#

对于获取响应头,它返回的是一个可迭代对象,您必须循环通过response.headers而不是log response.headers object
请尝试以下代码:

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

bf1o4zei4#

这是正确的,我面临这个问题,试试看。
它只能在服务器端(后端)解析。您必须添加后端响应标头,如下所示,

访问控制暴露接头:[内容-处置,.....可以添加多个标题]

之后,您可以使用response. header直接访问这个头文件

相关问题