2015-11-24 155 views
0

所以,我试图传输一个文件到客户端。继其他一些SO的答案,我现在有下面的代码(SB是StringBuilder):附加文件包含页面内容

HttpContext.Current.Response.Clear(); 
HttpContext.Current.Response.ClearHeaders(); 
HttpContext.Current.Response.ClearContent(); 

HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=export.csv"); 
HttpContext.Current.Response.ContentType = "text/csv"; 

HttpContext.Current.Response.Write(sb.ToString()); 

不过,我的问题是,我得到的expeted结果,然后在页面的源代码,其中包含我的按钮被附加到该文件。

回答

1

您需要您的代码后添加

Response.End(); 

。如果不是,Asp.Net将继续处理页面,这可能会导致发生在你身上的事情。

+0

我必须等待10-15分钟才能接受答案。我也试图理解这两个答案之间的差异是否相关。 –

1
string attachment = string.Empty; 
HttpResponse Response = HttpContext.Current.Response; 
Response.Clear(); 
Response.ClearHeaders(); 
Response.ClearContent(); 
Response.AddHeader("content-disposition", "attachment; filename=export.csv"); 
Response.ContentType = "text/csv"; 
Response.Write(sb.ToString()); 
Response.End(); 
+0

是否有任何理由做'HttpResponse响应= HttpContext.Current.Response'?我的意思是,除了更容易合作外。 –

+0

如果你在你的页面内,'this.Response'和'HttpContext.Current.Response'一样。如果你是例如在帮助程序类中...... –

+0

'HttpContext,封装有关单个HTTP请求的所有HTTP特定信息。你可以在MSDN上阅读'HttpContext.Current' – MethodMan