因浏览器JavaScript中只允许访问特定header
在浏览器中接收特定header需要在cores跨域设置中添加
在.net core中的setup.cs ConfigureServices方法中添加如下代码
services.AddCors(options =>
{
options.AddPolicy("AllowSome", policy =>
{
policy
.AllowAnyHeader().SetPreflightMaxAge(TimeSpan.FromSeconds(60))
.AllowAnyMethod()
.WithOrigins(Configuration["CorsAllowUrl"].ToStringArray())
.AllowCredentials()
.WithExposedHeaders("Content-Disposition");//允许浏览器访问额外的自定义头
});
});
且在Startup.cs的Configure 方法中添加如下代码
app.UseCors("AllowSome");
这样在请求返回结果中就可以拿到指定的header信息
举例:
/// <summary>
/// 导出报告
/// </summary>
/// <param name="projectId"></param>
/// <returns></returns>
[HttpPost("GenerateProjectDesignReport")]
public async Task<ActionResult> GenerateProjectDesignReport(int projectId)
{
if (projectId <= 0) return BadRequest("请求项目不存在");
var res = await _exportService.ExportReportWordAsync(projectId);
string filePath = res.downloadPath;
var contentType = res.contentType;
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
var fileName = HttpUtility.UrlEncode(res.projectName + "(" + DateTime.Today.ToString("yyyy-MM-dd") + ")" + ".docx");
return File(fileStream, contentType, fileName);
}
在返回的File中返回了filename相关信息,该信息在header头Content-Disposition中, 故想在浏览器中拿到该头, 就需要设置允许该头在浏览器中访问的设置.
如果自己想自定义一些头可以这样设置, 在return Ok();
前添加如下类似代码即可
Response.Headers.Add("file-name", "自定义header的内容");
网友评论