简体   繁体   中英

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.

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.

Try using Response.End() instead of Flush and Close

That's what I have been using in the past.

Have you tried setting the content type and calling 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:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM