0

I have an ASP.NET WebAPI method that returns a string containing a valid XML document:

public class MessageController : ApiController
{
    private readonly MyContextProvider _contextProvider = new MyContextProvider();

    [HttpGet]
    public string Message()
    {
        Message m =  _contextProvider.Context.Messages.First();
        return m.XMLFile;
    }
}

I call this method from the client using jQuery:

$.ajax('http://localhost:16361/service/api/message/message/', {
contentType: 'text/xml',
type: 'GET'
}).done(function (e) {  });

'e' contains the string of XML but this is not what I want. I would like to let the browser handling the response and showing its usual dialog box to save or open the XML. Obviously I'm missing something here but I'm not sure how to do it...

1 Answer 1

1

Take a look at this question here:

You can achieve this in WebApi by setting the content-disposition of the message content:

[HttpGet]
public HttpResponseMessage Message()
{
    Message m = _contextProvider.Context.Messages.First();
    var message =  Request.CreateResponse(HttpStatusCode.OK, m);
    message.Content.Headers.Add("Content-Disposition","attachment; filename=\"some.xml\"");
    return message;
}

OR

[HttpGet]
public HttpResponseMessage Message()
{
    Message m = _contextProvider.Context.Messages.First();
    var message = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(m, Encoding.UTF8, "application/xml")
        };
    message.Content.Headers.Add("Content-Disposition","attachment; filename=\"some.xml\"");
    return message;
}
3
  • My XML is stored on a string property of my Message entity. Therefore I do not hold an xml file so doing filename=\"some.xml\" is not going to work. How can I do something similar based on what I already have ?
    – Sam
    Commented Jul 17, 2013 at 13:49
  • @Sam Not sure I understand. My examples show it using your string property to make the XML. The name "some.xml" is simply to tell the browser what to name the file when the user gets the save as dialog. "some.xml" file doesn't need to actually exist(!).
    – Mark Jones
    Commented Jul 17, 2013 at 15:36
  • right, it was a misunderstanding. The second solution works great for me ! Thanks a lot for your help !
    – Sam
    Commented Jul 18, 2013 at 14:10

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.