1

I'm trying to write an XML file to the response when a button is clicked so the user can download the file. This works fine with an Excel file, but when I use the "text/xml" content type the file contains the expected contents, but with the webpage HTML appended to the end.

I assume since the button click is returning the page HTML it is merged with the file. I tried using Response.ClearContent() to try and clear the response, but it didn't work.

protected void Button1_Click(object sender, EventArgs e) {
    string fileName = "myFile.xml";
    string filePath = Server.MapPath("~/temp/myFile.xml");
    Response.ContentType = "text/xml";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    Response.ClearContent(); //I assumed this would clear the HTML before the file is written.
    Response.WriteFile(filePath);
    Response.Flush();
    File.Delete(filePath);
    Context.ApplicationInstance.CompleteRequest();
}

How do I make sure the page is not written to the XML file?

4

1 回答 1

4

HTML 是在按钮的事件引发Click呈现的,因此此时清除内容不会有任何效果。

尝试添加Response.End();到方法的末尾。

于 2013-04-24T13:30:09.470 回答