【问题标题】:Correct usage of Response.Write() in ASP.NET在 ASP.NET 中正确使用 Response.Write()
【发布时间】:2011-01-03 09:02:15
【问题描述】:

我试图在用户访问页面时强制下载 XML 文件。

这是我正在使用的代码

public partial class GenerateTemplate : LayoutsPageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //.............
        //Going about generating my XML
        //.............
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=template.xml");
        Response.Write(xmlDoc.InnerXml);
        Response.Flush();
        Response.Close();
    }
}

我面临的问题是我的下载窗口无限期挂起,而从未完成文件的下载/打开。

我做错了什么?我不是在这里处理任何对象或关闭任何连接吗?

【问题讨论】:

    标签: c# asp.net .net


    【解决方案1】:

    我已将a reply 发布到a similar question。引用我自己的话:

    只是对其他答案的一个小补充。在下载的最后我执行:

    context.Response.Flush();
    context.ApplicationInstance.CompleteRequest();
    

    我了解到,否则有时下载不会成功完成。

    This Google Groups posting 还注意到Response.End 会抛出一个ThreadAbortException,您可以通过使用CompleteRequest 方法来避免这种情况。

    【讨论】:

    • 以这种方式回复是否是一个好习惯,还是我应该仅将其作为评论发布到最初的问题?
    • CompleteRequest 和 Response.End 完全不同。 CompleteRequest 不会停止处理 ASP.NET 管道的其余部分;它只影响 HTTP 管道。您处于 HTTP 管道的 ASP.NET 部分,除非您调用 Response.End,否则 asp.net 处理程序将继续处理。
    【解决方案2】:

    尝试使用Response.End() 代替FlushClose

    这就是我过去一直使用的。

    【讨论】:

      【解决方案3】:

      您是否尝试过设置内容类型并调用Response.End()

      protected void Page_Load(object sender, EventArgs e)
      {
          //.............
          //Going about generating my XML
          //.............
          Response.Clear();
          Response.ContentType = "text/xml";        
          Response.AddHeader("Content-Disposition", "attachment; filename=template.xml");
          Response.Write(xmlDoc.InnerXml);
          Response.End();
      }
      

      【讨论】:

        【解决方案4】:

        你说你想要一个文件下载使用 asp.net 网络表单你会这样做:

        context.Response.ContentType = //MIME type
        
        // Set the filename 
        context.Response.AddHeader("content-disposition", "attachment;filename=" + queryFile); 
        
        // Stream the file to the client 
        context.Response.WriteFile(file);
        

        【讨论】:

        • 我在物理服务器中没有文件。 XML 文件作为 XMLDocument 对象存在于内存中。因此,我不能使用 WriteFile() 方法。
        • 好的!抱歉,我认为WriteFile 方法会有一个需要流的重载(就像mvc 的controller.File 一样)也许你可以尝试写入输出流。见:msdn.microsoft.com/en-us/library/…
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-05
        • 2012-09-26
        • 1970-01-01
        • 1970-01-01
        • 2011-02-12
        • 1970-01-01
        相关资源
        最近更新 更多