You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET中Chrome等浏览器Content-Disposition inline无法正常下载PDF问题

问题:文件下载时文件名被浏览器替换为ASPX页面名

原始代码

byte[] byteData= GetByteData(this.reportContent);
response.Clear();
response.ClearContent();
response.ClearHeaders();
 
response.Buffer = true;
response.AddHeader("Accept-Header", byteData.Length.ToString());
response.ContentType ="application/pdf";
response.Charset = "utf-8";
response.AddHeader("Accept-Ranges", "bytes");
string cd = $"inline;filename=myReport-123.pdf";
response.AddHeader("Content-Disposition", cd.ToString().Trim());
response.AddHeader("Content-Length", byteData.Length.ToString());
if (byteData.Length > 0)
    response.BinaryWrite(byteData);

response.Flush();
response.Close();

问题现象

本地localhost访问时文件名正常显示为myReport-123.pdf,但通过IP地址(如https://192.168.1.1/.../report.aspx)访问时,Chrome、IE、Edge浏览器下载文件时文件名会被强制替换为Report.aspx,Firefox无此异常。尝试添加Content-Transfer-Encoding: Binary等方案均无效。

解决方案

问题根源在于Content-Disposition头格式不规范,部分浏览器会优先从URL路径提取文件名作为 fallback。调整以下几点即可修复:

  • 规范Content-Disposition格式,给文件名添加双引号,同时增加filename*参数兼容多浏览器(符合RFC 5987标准)
  • 移除不必要的Charset和Accept-Header头(PDF是二进制文件,无需设置utf-8编码)
  • 确保响应头优先级高于URL路径的文件名解析

修复后的代码:

byte[] byteData = GetByteData(this.reportContent);
response.Clear();
response.ClearContent();
response.ClearHeaders();

response.Buffer = true;
response.ContentType = "application/pdf";
// 二进制文件无需指定文本编码,移除Charset干扰
response.Charset = string.Empty;
response.AddHeader("Accept-Ranges", "bytes");

// 规范Content-Disposition,添加双引号和兼容参数
string fileName = "myReport-123.pdf";
string contentDisposition = $"inline; filename=\"{fileName}\"; filename*=UTF-8''{Uri.EscapeDataString(fileName)}";
response.AddHeader("Content-Disposition", contentDisposition);
response.AddHeader("Content-Length", byteData.Length.ToString());

if (byteData.Length > 0)
    response.BinaryWrite(byteData);

response.Flush();
// 使用Response.End()确保ASP.NET正确终止响应,避免后续输出干扰
response.End();

关键说明

  • 双引号包裹文件名:避免文件名包含空格或特殊字符时解析失败
  • filename*参数:强制浏览器优先使用该参数指定的文件名,而非URL中的页面名,同时兼容非ASCII文件名的解析
  • 移除Charset:PDF是二进制文件,设置utf-8编码会干扰浏览器的MIME类型判断

内容的提问来源于stack exchange,提问作者arpit rai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 14:22:48