【发布时间】:2016-10-04 22:57:00
【问题描述】:
关于正确使用Response.End() 有很多(很多)SO 和其他线程,但是,似乎没有一个与我们在多年未更改的代码中看到的行为相匹配。
行为:下载文件时,页面的 HTML 内容会附加到文件内容中。
项目类型: WebForms
.NET 版本: 4.6.2 | 4.5.0 | 4.0.0
VS 版本: 2015 | 2013 | 2012(开启/不开启安全模式)
WebHost: IIS Express(默认设置)
创建一个空白的 WebForms 项目。删除所有引用,但;
- 系统
- System.Web
Default.aspx(从默认模板中提取)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestDownload2.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sample page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="_uiExportBtn" runat="server" Text="Download" OnClick="_uiExportBtn_Click" />
</form>
</body>
</html>
默认.aspx.cs
namespace TestDownload
{
using System;
using System.IO;
using System.Threading;
public partial class _Default : Page
{
protected void _uiExportBtn_OnClick(object sender, EventArgs e)
{
try
{
string filePath = Server.MapPath("~/File1.txt");
FileInfo fileDetails = new FileInfo(filePath);
Response.Clear();
Response.AddHeader("Content-Disposition",
"attachment; filename=" + Path.GetFileName(filePath)); // strip out the path
Response.AddHeader("Content-Length", fileDetails.Length.ToString());
Response.ContentType = "text/plain";
Response.WriteFile(filePath);
Response.Flush();
Response.End();
}
catch (ThreadAbortException)
{
Thread.ResetAbort();
}
}
}
}
File1.txt 的内容
File with sample data that can be downloaded.
点击下载时的文件内容;
File with sample data that can be downloaded.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
Sample page
</title></head>
<body>
<form method="post" action="./Default.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTQ2OTkzNDMyMWRk3Rw04QLdhpy5d4I1K2wRBGQwJyDyRwQJv3qrWVnmZOk=" />
</div>
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="CA0B0334" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAIM+aT11BIx7AHRURAAeZqgtB4HvaHnJdET69NHLAgDcsjxSqzk6G3joivJ/c73mKUQf4CSnfdxrC8NepO7KQg3" />
</div>
<input type="submit" name="_uiExportBtn" value="Download" id="_uiExportBtn" />
</form>
</body>
</html>
编辑 在对不同的浏览器、VS 版本、.NET 版本进行大量试验以缩小范围后,问题似乎是在 IIS 上注册的指定 MIME 类型。
这似乎是我第二次遇到this issue。我使用了类似的解决方法,但我仍然对原因感到困惑。
【问题讨论】: