How to send xml via HTTP request and receive it using ASP.NET MVC?

I am trying to send an xml string via an HTTP request and get it at the other end. At the end of the tutorial, I always get the xml to be null. Can you tell me why this is?

Send:

var url = "http://website.com"; var postData = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><xml>...</xml>"; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData); var req = (HttpWebRequest)WebRequest.Create(url); req.ContentType = "text/xml"; req.Method = "POST"; req.ContentLength = bytes.Length; using (Stream os = req.GetRequestStream()) { os.Write(bytes, 0, bytes.Length); } string response = ""; using (System.Net.WebResponse resp = req.GetResponse()) { using (StreamReader sr = new StreamReader(resp.GetResponseStream())) { response = sr.ReadToEnd().Trim(); } } 

Reception:

 [HttpPost] [ValidateInput(false)] public ActionResult Index(string xml) { //xml is always null ... return View(model); } 
+7
c # post asp.net-mvc-4
source share
2 answers

I managed to get this to work like this:

 [HttpPost] [ValidateInput(false)] public ActionResult Index() { string xml = ""; if(Request.InputStream != null){ StreamReader stream = new StreamReader(Request.InputStream); string x = stream.ReadToEnd(); xml = HttpUtility.UrlDecode(x); } ... return View(model); } 

However, I'm still wondering why using xml as a parameter does not work.

+10
source

I believe this is because you specified req.ContentType = "text/xml"; .

If I remember correctly when you define your controller using a "primitive" type ( string here is a "primitive" type)

 public ActionResult Index(string xml){} 

MVC will try to find xml either in the query string or in the published form data (html input field). But if you send something more complex to the server, MVC will transfer it to a specific class.

For example, when uploading multiple files to the server, you can accept them as follows in your controller

 public ActionResult Index(IEnumerable<HttpPostedFileBase> files){} 

Therefore, I assume that you should accept the text/xml stream in the controller using the correct class.

Update:

It seems that there is no such class because you are accepting a data stream (and this does not come from the input element). You can write your own binder to accept the XML document. See Discussions below.

Reading text / xml in ASP.MVC controller

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

0
source

All Articles