Search code examples
javascriptc#xmlrestwcf

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.


Solution

  • 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;
        }
    
    
    
        }