Search code examples
asp.net-mvcasp.net-web-apixmldocument

How to receive XmlDocument in MVC 4 Web Api?


I am posting XmlDocument to ApiController (from windows service, service is working fine, it is posting correct, I used it in wcf web API), but XML is always null, what am I doing wrong?

I can post some class, such in tutorials, or Get any data and everything will be ok, but I can't post XmlDocument.

public class XmlController : ApiController
{
    public void PostXml(XmlDocument xml)
    {
       // code
    }
}

Solution

  • I've found a solution:

    We need to use inheritance to inherit MediaTypeFormatter

    public class XmlMediaTypeFormatter : MediaTypeFormatter
    {
        public XmlMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));      
        }
    
        public override System.Threading.Tasks.Task<object> ReadFromStreamAsync(Type type, Stream stream,
             HttpContentHeaders contentHeaders,
             IFormatterLogger formatterLogger)
        {
            var taskCompletionSource = new TaskCompletionSource<object>();
            try
            {
                var memoryStream = new MemoryStream();
                stream.CopyTo(memoryStream);
                var s = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
    
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(s);
    
                taskCompletionSource.SetResult(xmlDoc);
            }
            catch (Exception e)
            {
                taskCompletionSource.SetException(e);
            }
            return taskCompletionSource.Task;
        }
    
        public override bool CanReadType(Type type)
        {
            return type == typeof(XmlDocument);
        }
    
        public override bool CanWriteType(Type type)
        {
            return false;
        }
    }
    

    Then register it in Global.asax:

    GlobalConfiguration.Configuration.Formatters.Insert(0, new XmlMediaTypeFormatter());
    

    Controller:

    public HttpResponseMessage PostXml([FromBody] XmlDocument xml)
        {//code...}