Created
September 27, 2012 06:45
-
-
Save carlosrivera/3792548 to your computer and use it in GitHub Desktop.
XML ActionResult for ASM MVC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
public class HomeController : Controller | |
{ | |
public ActionResult Index() | |
{ | |
return new XMLActionResult<MyClass>( | |
new MyClass | |
{ | |
Data = "Hello, World!" | |
}); | |
} | |
} | |
// ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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