2016-10-04 68 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文件。