ASP.NET MVC 2 ActionResults for XML, JSONP, and RSS
Needing a reusable way to return XML, JSONP, and RSS from action methods in my MVC 2 controllers, I created three types of action results to handle the work.
XML
public class XmlResult<T> : ActionResult
{
public T Obj { get; set; }
public XmlResult(T obj)
{
this.Obj = obj;
}
public override void ExecuteResult(ControllerContext context)
{
var xs = new System.Xml.Serialization.XmlSerializer(this.Obj.GetType());
context.HttpContext.Response.ContentType = "text/xml";
xs.Serialize(context.HttpContext.Response.Output, this.Obj);
}
}
JSONP
public class JsonpResult<T>: ActionResult
{
public T Obj { get; set; }
public string CallbackName { get; set; }
public JsonpResult(T obj, string callback)
{
this.Obj = obj;
this.CallbackName = callback;
}
public override void ExecuteResult(ControllerContext context)
{
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonp = this.CallbackName + "(" + js.Serialize(this.Obj) + ")";
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.Write(jsonp);
}
}
RSS
public class RssResult : ActionResult
{
public SyndicationFeed Feed { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var rss = new Rss20FeedFormatter(Feed);
context.HttpContext.Response.ContentType = "application/rss+xml";
using (var writer = System.Xml.XmlWriter.Create(context.HttpContext.Response.Output))
{
rss.WriteTo(writer);
}
}
}