有很多(许多)SO和其他线程关于Response.End()
的正确使用,但是,没有一个看起来与我们在代码中看到的行为相匹配多年。Response.End()不会阻止附加html
行为:当下载一个文件,网页的HTML内容附加到文件内容。
项目类型:的WebForms
.NET版本: 4.6.2 | 4.5.0 | 4.0.0
VS版本: 2015年| 2013 | 2012(有/无安全模式开启)
虚拟主机提供商: IIS快递(默认设置)
创建一个空白的WebForms项目。删除所有参考,但;
- 系统
- 的System.Web
Default.aspx的(从默认模板stipped)
<%@ 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>
Default.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();
}
}
}
}
文件1的内容.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第二次。我使用了类似的解决方法,但我仍然因为这个原因而感到困惑。