I'm trying to generate XML file on the fly and download it to the requesting browser (client's machine) in ASP.NET Core 5.0.
I tried this one with no luck:
public Task GenerateXML()
{
// here I just created the XmlDocument
XmlDocument doc = new XmlDocument();
// and then created the xml declaration, root element and sub elements
..........
// here are the codes to export the XML file to the requesting browser
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8);
doc.WriteTo(writer);
writer.Flush();
Response.Clear();
byte[] byteArray = stream.ToArray();
Response.Headers.Append("Content-Disposition", "filename=Books.xml");
Response.Headers.Append("Content-Length", byteArray.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Body.Write(byteArray);
writer.Close();
}
I tried to use your code to accomplish this, in fact, your code is working and the file can be downloaded, but the download prompt box does not appear.
When you open your browser's download list, the file should appear in your list.
I use JavaScript to call this method, the download prompt box appears normally and the file can be downloaded.
Below is my test code,you can refer to it:
Controller:
JavaScript:
Test Result:
Hope this will help you.