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...

Sam
  • 13,934
  • 26
  • 108
  • 194

1 Answers1

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;
}
Community
  • 1
  • 1
Mark Jones
  • 12,156
  • 2
  • 50
  • 62
  • 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 Jul 17 '13 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 Jul 17 '13 at 15:36
  • right, it was a misunderstanding. The second solution works great for me ! Thanks a lot for your help ! – Sam Jul 18 '13 at 14:10