【问题标题】:Attached file contains page's content附件包含页面内容
【发布时间】:2015-11-24 20:20:46
【问题描述】:

所以,我正在尝试向客户端传输文件。在其他一些 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 结果,然后将包含我的按钮的页面的源代码附加到文件中。

【问题讨论】:

    标签: c# asp.net attachment


    【解决方案1】:

    你需要添加一个

    Response.End();
    

    在您的代码之后。如果没有,Asp.Net 将继续处理该页面,这可能会导致发生在您身上的事情。

    【讨论】:

    • 我必须等待 10-15 分钟才能接受答案。我也试图了解 2 个答案之间的差异是否相关。
    【解决方案2】:
    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();
    

    【讨论】:

    • 有什么理由做HttpResponse Response = HttpContext.Current.Response吗?我的意思是,除了更容易使用之外。
    • 如果您在您的页面内,this.ResponseHttpContext.Current.Response 相同。如果你是例如在助手类中...
    • HttpContext, Encapsulates all HTTP-specific information about an individual HTTP Request。你可以在 MSDN 上阅读 HttpContext.Current
    • 如果不声明响应Response.ClearContent(),我也可以不执行以下操作如果您想了解有关HTTPContext 的更多信息,那么您可以检查本地调试时可用的所有属性
    • @MethodMan 让我重新表述一下:创建一个新的HttpResponse myResponse 是否比简单地使用HttpContext.Current.Response 有任何好处。基本上,你的第二行的目的是什么。
    猜你喜欢
    • 2013-06-25
    • 2021-08-08
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多