Created
October 20, 2014 22:45
-
-
Save kcuzner/eef239003d4f99dfacea to your computer and use it in GitHub Desktop.
XML Media Type Formatter which handles namespaces
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.Net.Http.Formatting; | |
using System.Net.Http.Headers; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Web; | |
using System.Xml; | |
using System.Xml.Serialization; | |
namespace WebApp.Infrastructure | |
{ | |
public class NamespacedXmlMediaTypeFormatter : XmlMediaTypeFormatter | |
{ | |
const string xmlType = "application/xml"; | |
const string xmlType2 = "text/xml"; | |
public XmlSerializerNamespaces Namespaces { get; private set; } | |
Dictionary<Type, XmlSerializer> Serializers { get; set; } | |
public NamespacedXmlMediaTypeFormatter() | |
: base() | |
{ | |
this.Namespaces = new XmlSerializerNamespaces(); | |
this.Serializers = new Dictionary<Type, XmlSerializer>(); | |
} | |
public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext) | |
{ | |
lock (this.Serializers) | |
{ | |
if (!Serializers.ContainsKey(type)) | |
{ | |
var serializer = new XmlSerializer(type); | |
//we add a new serializer for this type | |
this.Serializers.Add(type, serializer); | |
} | |
} | |
return Task.Factory.StartNew(() => | |
{ | |
XmlSerializer serializer; | |
lock (this.Serializers) | |
{ | |
serializer = Serializers[type]; | |
} | |
var xmlWriter = new XmlTextWriter(writeStream, Encoding.UTF8); | |
xmlWriter.Namespaces = true; | |
serializer.Serialize(xmlWriter, value, this.Namespaces); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment