1

I have a Web API 2 POST endpoint which takes a parameter, queries the database and returns an xml string as the response.

public async Task<IHttpActionResult> Post(long groupId)
{
    People people = await _someService.GetPeople(groupId);
    XElement peopleXml = _xmlService.ConverToXml(people);
    return Ok(peopleXml);
}

How do I to return the xml as a file instead?

1

1 Answer 1

2

Figured it out myself, but I hope there is a simpler way -

public async Task<IHttpActionResult> Post(long groupId)
{
    People people = await _someService.GetPeople(groupId);
    XElement peopleXml = _xmlService.ConverToXml(people);
    byte[] toBytes = Encoding.Unicode.GetBytes(peopleXml.ToString());

    var stream = new MemoryStream(toBytes);

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StreamContent(stream)
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.txt"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");

    var response = ResponseMessage(result);
    return response;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.