[英]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.