How to serialize XML to Action method parameters in ASP.NET MVC 2
Our current web site need to integrate with partners' sites in which XML (with Http Post) is uesed as communication protocol.
Do you know how to map XML elements, like below, to Action me开发者_Python百科thod parameters?
<?xml version="1.0" encoding="utf-8"?>
<xBalance>
<MemberCode>bu00001</MemberCode>
</xBalance>
Thanks.
You could use a custom model binder. Start with a view model which will represent this XML structure:
[XmlRoot("xBalance")]
public class XBalance
{
public string MemberCode { get; set; }
}
then write a custom model binder for this view model:
public class XBalanceModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
using (var reader = XmlReader.Create(controllerContext.HttpContext.Request.InputStream))
{
var serializer = new XmlSerializer(typeof(XBalance));
return serializer.Deserialize(reader);
}
}
}
which will be registered in Application_Start
:
ModelBinders.Binders.Add(typeof(XBalance), new XBalanceModelBinder());
Now your controller action might look like this:
[HttpPost]
[ValidateInput(false)]
public ActionResult Index(XBalance model)
{
...
}
You might need to decorate your action with the [ValidateInput(false)]
attribute as you will be POSTing XML to it and ASP.NET doesn't like characters such as <
and >
to be sent to the server.
精彩评论