How to POST XML into MVC Controller? (instead of key/value) How to POST XML into MVC Controller? (instead of key/value) xml xml

How to POST XML into MVC Controller? (instead of key/value)


You cannot directly pass XML data as file to MVC controller. One of the best method is to pass XML data as Stream with HTTP post.

For Posting XML,

  1. Convert the XML data to a Stream and attached to HTTP Header
  2. Set content type to "text/xml; encoding='utf-8'"

Refer to this stackoverflow post for more details about posting XML to MVC Controller

For retrieving XML in the controller, use the following method

[HttpPost] public ActionResult Index(){    HttpWebResponse response = (HttpWebResponse)request.GetResponse();    if (response.StatusCode == HttpStatusCode.OK)    {        // as XML: deserialize into your own object or parse as you wish        var responseXml = XDocument.Load(response.GetResponseStream());        //in responseXml variable you will get the XML data    }}


This seems to be the way to pay XML to a MVC Controller

How to pass XML as POST to an ActionResult in ASP MVC .NET

I tried to get this to work with WEB API but could not so I have to used the MVC 'Controller' instead.


In order to pass the data as a sting in MVC you have to create your own media type formatter to handle plain text. Then add the formatter to the config section.

To use the new formatter specify the Content-Type for that formatter, like text/plain.

Sample formatter for text

using System;using System.Net.Http.Formatting;using System.Net.Http.Headers;using System.Threading.Tasks;using System.IO;using System.Text;namespace SampleMVC.MediaTypeFormatters{    public class TextMediaTypeFormmatter : XmlMediaTypeFormatter    {        private const int ByteChunk = 1024;        private UTF8Encoding StringEncoder = new UTF8Encoding();        public TextMediaTypeFormmatter()        {            base.UseXmlSerializer = true;            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));        }        public override bool CanReadType(Type type)        {            if (type == typeof(string))            {                return true;            }            return false;        }        public override bool CanWriteType(Type type)        {            if (type == typeof(string))            {                return true;            }            return false;        }        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)        {            StringBuilder StringData = new StringBuilder();            byte[] StringBuffer = new byte[ByteChunk];            int BytesRead = 0;            Task<int> BytesReadTask = readStream.ReadAsync(StringBuffer, 0, ByteChunk);            BytesReadTask.Wait();            BytesRead = BytesReadTask.Result;            while (BytesRead != 0)            {                StringData.Append(StringEncoder.GetString(StringBuffer, 0, BytesRead));                BytesReadTask = readStream.ReadAsync(StringBuffer, 0, ByteChunk);                BytesReadTask.Wait();                BytesRead = BytesReadTask.Result;            }            return Task<object>.Run(() => BuilderToString(StringData));        }        private object BuilderToString(StringBuilder StringData)        {            return StringData.ToString();        }        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)        {            byte[] StringBuffer = StringEncoder.GetBytes((string)value);            return writeStream.WriteAsync(StringBuffer, 0, StringBuffer.Length);        }    }}

Controller method:

[HttpPost]public async Task<HttpResponseMessage> UsingString([FromBody]string XmlAsString){    if (XmlAsString == null)    {        return this.Request.CreateResponse(HttpStatusCode.BadRequest);    }    return this.Request.CreateResponse(HttpStatusCode.OK, new { });}

Setup in the WebApiConfig.cs Register method:

config.Formatters.Add(new TextMediaTypeFormmatter());

Fiddler headers:

User-Agent: FiddlerContent-Type: text/plain