0

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 method parameters?

<?xml version="1.0" encoding="utf-8"?>
<xBalance>
    <MemberCode>bu00001</MemberCode>
</xBalance>

Thanks.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.