Search code examples
xmlasp.net-mvcfiddler

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


Using Fiddler I can pass in the body

someXml=ThisShouldBeXml

and then in the controller

    [HttpPost]
    public ActionResult Test(object someXml)
    {
        return Json(someXml);
    }

gets this data as a string

How do I get fiddler to pass XML to the MVC ActionController ? If I try setting the value in the body as raw xml it does not work..

And for bonus points how do I do this from VBscript/Classic ASP?

I currently have

DataToSend = "name=JohnSmith"

          Dim xml
         Set xml = server.Createobject("MSXML2.ServerXMLHTTP")
   xml.Open "POST", _
             "http://localhost:1303/Home/Test", _
             False
 xml.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
 xml.send DataToSend

Solution

  • 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
        }
    }