[英]Correct usage of Response.Write() in ASP.NET
I am trying to force a download of an XML file when the user visits a page. 我试图在用户访问页面时强制下载XML文件。
This is the code I am using 这是我正在使用的代码
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();
}
}
I am facing a problem that my download window hangs indefinitely, without ever completing the download/Open of the file. 我遇到一个问题,我的下载窗口无限期地挂起,而从未完成文件的下载/打开。
What am I doing wrong? 我究竟做错了什么? Am I not disposing any objects or closing any connections here? 我在这里没有布置任何对象或关闭任何连接吗?
I've posted a reply to a similar question . 我已经发布了对类似问题 的答复 。 To quote myself: 引用我自己:
Just a small addition to the other answers. 只是其他答案的一小部分。 At the very end of a download I execute: 在下载的最后,我执行:
context.Response.Flush();
context.ApplicationInstance.CompleteRequest();
I learned that otherwise, the download sometimes does not complete successfully. 我了解到,否则下载有时无法成功完成。
This Google Groups posting also notes that Response.End
throws a ThreadAbortException
which you could avoid by using the CompleteRequest
method. 此Google网上论坛帖子还指出, Response.End
引发ThreadAbortException
,您可以通过使用CompleteRequest
方法来避免这种情况。
Try using Response.End()
instead of Flush
and Close
尝试使用Response.End()
而不是Flush
and Close
That's what I have been using in the past. 那就是我过去一直在使用的东西。
Have you tried setting the content type and calling Response.End()
: 您是否尝试过设置内容类型并调用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();
}
You say you want to have a file download With asp.net web forms you would do this: 您说要下载文件,请使用asp.net Web表单执行以下操作:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.