Search code examples
javascriptc#wcfasp.net-web-api

How to return xml file using memorystream and web api


I have WebApp (using WCF), which backend of app in C# and front side in JS. I need to create webservice which will read data from Oracle database and based on those datas create XML file. Need to save file to MemoryStream and using ajax (js) in front side download this XML file.

If anyone understand what I need to do, please share samples of code or usefull infromation links. If I coudnt explain well ask me for more details, I can share.


Solution

  • On StackOverflow you should be providing code examples of what you've tried, so we can help debug the issue, not write the code for you. That being said, here's a starting point for you:

    You can return a FileContentResult object from your WebAPI controller that returns an ActionResult:

    return File(byte[] fileContents, string contentType, string? fileDownloadName);
    

    To build the XML file, you should be able to parse a simple one out yourself easily enough with a StringBuilder or something. If you need something more complicated, look into Microsoft's DocumentFormat.OpenXml NuGet package (though I've only used it to build .xlsx files), and note that you should be able to use a MemoryStream when creating a document. From that memory stream you can get the byte[] required for the FileContentResult return object in your WebAPI endpoint.

    As for using an Ajax query to get the download... Take a look here and here for suggestions on how to handle downloading a file via JavaScript and pick your preferred option.