Skip to content

Instantly share code, notes, and snippets.

@carlosrivera
Created September 27, 2012 06:45
Show Gist options
  • Save carlosrivera/3792548 to your computer and use it in GitHub Desktop.
Save carlosrivera/3792548 to your computer and use it in GitHub Desktop.
XML ActionResult for ASM MVC
// ...
public class HomeController : Controller
{
public ActionResult Index()
{
return new XMLActionResult<MyClass>(
new MyClass
{
Data = "Hello, World!"
});
}
}
// ...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace API_backend.Infrastructure
{
public class XMLActionResult<T> : ActionResult
{
private static UTF8Encoding encoding = new UTF8Encoding(false);
public T Data { get; set; }
public Type[] IncludedTypes = new[] { typeof(object) };
public XMLActionResult(T data)
{
Data = data;
}
public XMLActionResult(T data, Type[] extraTypes)
{
Data = data;
IncludedTypes = extraTypes;
}
public override void ExecuteResult(ControllerContext context)
{
using (MemoryStream stream = new MemoryStream())
{
using (var xmlWriter =
XmlTextWriter.Create(stream,
new XmlWriterSettings()
{
OmitXmlDeclaration = true,
Encoding = encoding,
Indent = true
}))
{
new XmlSerializer(typeof(T), IncludedTypes)
.Serialize(xmlWriter, Data);
}
new ContentResult
{
ContentType = "text/xml",
Content = encoding.GetString(stream.ToArray()),
ContentEncoding = encoding
}.ExecuteResult(context);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment