Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

download xml file asp.net web api

public class OkXmlDownloadResult : IHttpActionResult
{
    private readonly ApiController _controller;

    public OkXmlDownloadResult(string xml, string downloadFileName,
        ApiController controller)
    {
        if (xml == null)
        {
            throw new ArgumentNullException("xml");
        }

        if (downloadFileName == null)
        {
            throw new ArgumentNullException("downloadFileName");
        }

        if (controller == null)
        {
            throw new ArgumentNullException("controller");
        }

        Xml = xml;
        ContentType = "application/xml";
        DownloadFileName = downloadFileName;
        _controller = controller;
    }

    public string Xml { get; private set; }

    public string ContentType { get; private set; }

    public string DownloadFileName { get; private set; }

    public HttpRequestMessage Request
    {
        get { return _controller.Request; }
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(Execute());
    }

    private HttpResponseMessage Execute()
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StringContent(Xml);
        response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(ContentType);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = DownloadFileName
        };
        return response;
    }
}

// Use this below code in controller 
public class ValuesController : ApiController
{
    public IHttpActionResult Get()
    {
        User user = new User()
        {
            FirstName = "First",
            LastName = "Last"
        };

        // Alternative 1
        XmlSerializer serializer = new XmlSerializer(typeof(User));

        // Alternative 2
        // DataContractSerializer serializer = new DataContractSerializer(typeof(User));

        StringBuilder builder = new StringBuilder();
        using (StringWriter writer = new StringWriter(builder))
        {
            serializer.Serialize(writer, user);

            // alternative 2
            // serializer.WriteObject(writer, user);
        }

        // create XML from your data.
        return new OkXmlDownloadResult(builder.ToString(), "myfile.xml", this);
    }
}

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #download #xml #file #web #api
ADD COMMENT
Topic
Name
6+1 =