Question

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?

Was it helpful?

Solution

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; }
    }
}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top