Reading text / xml in ASP.MVC controller

How to read text / xml in action on an ASP.MVC controller?

I have a web application that can receive POSTed Xml from two different sources, so the contents of Xml may be different.

I want the default action on my controller to be able to read Xml, but I'm struggling to figure out how I can get the Xml in action in the first place.

If the Xml was consistent, I could use model binding, but this is not possible here.

+6
xml asp.net-mvc controller action
source share
1 answer

You can read it from the request stream:

[HttpPost] public ActionResult Foo() { using (var reader = new StreamReader(Request.InputStream)) { string xml = reader.ReadToEnd(); // process the XML ... } } 

and to clear this action, you can write a custom mediator for XDocument:

 public class XDocumentModeBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { return XDocument.Load(controllerContext.HttpContext.Request.InputStream); } } 

which you would register in Application_Start :

 ModelBinders.Binders.Add(typeof(XDocument), new XDocumentModeBinder()); 

and finally:

 [HttpPost] public ActionResult Foo(XDocument doc) { // process the XML ... } 

which is clearly cleaner.

+14
source share

All Articles