简体   繁体   中英

Download XML file with JavaScript and C#/Rest

I have an xml document that I generated in C#, I would like to return the string/document via WCF/REST so it will be downloaded by the browser. What is the operationcontract/return type that I should use? And how can I get it to be prompted to save by javascript and the browser.

I had the similar issue with NodeJS backend.

I returned XML as a string and then on front-end I used next code:

 <a href="data:text/xml,HERE WILL BE YOUR XML" download="filename.xml">Download</a>

Your operation contract should not be one way and you should return Stream

    [OperationContract(IsOneWay = false)]
    [WebGet(UriTemplate = "GetXml/{xmlFileName}")]
    Stream GetXml(string xmlFileName);

     public Stream GetXml(string xmlFileName)
    {
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";

    string xmlLocation=GetXmlLocation(xmlFileName);

    try
    {
      return File.OpenRead(xmlLocation);
    }
    catch
    {
       // File Not Found

       return null;
    }



    }

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