1

In a Controller in my ASP.Net MVC app, I serialize a class, and am trying to offer up the contents for immediate download.

So far, I've got my controller returning a FileStreamResult

    public FileStreamResult Create(MyViewMode vm)
    {
        var xml= _mySerializer.SerializeToXml(vm);

        var ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
        return new FileStreamResult(ms, "application/xml");
    }

This works, however it's outputting the XML in the browser.

Is there a way I can have it download the file as MyXml.xml for example?

Alex
  • 37,502
  • 51
  • 204
  • 332
  • 1
    I think this is up to the browser to determine what to do with the content based on MIME type rather than your code – Tommy Oct 23 '12 at 16:47
  • Have you tried to add `content-disposition` `attachment` to the head of the page? – Zabavsky Oct 23 '12 at 16:55

2 Answers2

4

This seems to do what you want:

public class HomeController : Controller
{
    public ActionResult MyXml()
    {
        var obj = new MyClass {MyString = "Hello", MyInt = 42, MyBool = true};
        var ser = new XmlSerializer(typeof(MyClass));
        var stream = new MemoryStream();
        ser.Serialize(stream, obj);
        stream.Position = 0;
        return File(stream, "application/xml", "MyXml.xml");
    }

    public class MyClass
    {
        public string MyString { get; set; }
        public int MyInt { get; set; }
        public bool MyBool { get; set; }
    }
}
Joseph Sturtevant
  • 13,194
  • 12
  • 76
  • 90
  • This is working, however I can't return a view / redirect after the file has downloaded. Separate question - http://stackoverflow.com/questions/13065697/redirect-show-view-after-generated-file-is-dowloaded – Alex Oct 25 '12 at 09:37
0

Can you use XmlDocument() and write the XML to it and then use Save property?

Learner
  • 3,904
  • 6
  • 29
  • 44