XmlResult for ASP.Net MVC

by Mwwhited 7. June 2009 05:06

Not sure why Microsoft didn't include a ActionResult that supported XML but here you go. This version will directly support XNode, XmlNode, Data Contracts, and then try to use the standard XmlSerializer. Enjoy...


using System;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using WhitedUS.Common;

namespace WhitedUS.Web.Mvc
{
    public class XmlResult : ActionResult
    {
        public XmlResult() { }
        public XmlResult(object data) { this.Data = data; }

        public string ContentType { get; set; }
        public Encoding ContentEncoding { get; set; }
        public object Data { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;
            if (!string.IsNullOrEmpty(this.ContentType))
                response.ContentType = this.ContentType;
            else
                response.ContentType = ContentTypes.Text_XML;

            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;

            if (this.Data != null)
            {
                if (this.Data is XmlNode)
                    response.Write(((XmlNode)this.Data).OuterXml);
                else if (this.Data is XNode)
                    response.Write(((XNode)this.Data).ToString());
                else
                {
                    var dataType = this.Data.GetType();
                    if (dataType.GetCustomAttributes(typeof(DataContractAttribute), true).FirstOrDefault() != null)
                    {
                        var dSer = new DataContractSerializer(dataType);
                        dSer.WriteObject(response.OutputStream, this.Data);
                    }
                    else
                    {
                        var xSer = new XmlSerializer(dataType);
                        xSer.Serialize(response.OutputStream, this.Data);
                    }
                }
            }
        }
    }
}

Tags: , , ,

Programming

Comments

7/30/2011 10:08:10 AM #

pingback

Pingback from prosglobal.tv

Build truly RESTful API and website using same ASP.NET MVC code  |  Pros Global TV

prosglobal.tv

6/10/2014 2:09:38 PM #

pingback

Pingback from thiencdt.wordpress.com

Build Truly RESTful API and Website using Same ASP.NET MVC Code |

thiencdt.wordpress.com

Comments are closed

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen