2016-10-04 69 views
0

有很多(许多)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第二次。我使用了类似的解决方法,但我仍然因为这个原因而感到困惑。

回答

0

做进一步的研究之后,我想我可以提供一个可能的解释,为什么我们得到上面的行为。如指定here关于如何设置MIME类型以及浏览器如何解释它们,似乎通过在我的文件上指定text/palintext/csv,浏览器将其解释为与text/html(已显示的页面)相同,并将当前页面内容添加到该文件的HTTP响应。

需要注意的是附加的HTML实际上不作为文件响应然而,浏览器仍然会重视它,如果它认为该文件是相同类型的内容页面的一部分传输是非常重要的。

至于解决方案,并从什么文章介绍,为了分离出来自HTTP响应的其余部分文件之后,它应该被标记为application/octet-stream尤其在实例所在的文件实际上包含文本非常容易解释为HTML内容,如.txt.csv文件。