Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send xml through an HTTP request, and receive it using ASP.NET MVC?

I am trying to send an xml string through an HTTP request, and receive it on the other end. On the receiving end, I am always getting that the xml is null. Can you tell me why that 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();
        }
     }

Receive:

[HttpPost]
[ValidateInput(false)]
public ActionResult Index(string xml)
{
    //xml is always null
    ...
    return View(model);
}
like image 492
Kalina Avatar asked Aug 19 '13 18:08

Kalina


1 Answers

I was able to get this working like so:

[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 am still curious why taking the xml as a parameter does not work.

like image 193
Kalina Avatar answered Nov 03 '22 02:11

Kalina