Sending XML to an ASP.NET MVC Action Method Argument

I read a great article recently by Phil Haack on sending JSON to an action method. This was very timely as I wanted to do exactly that in the REST API I've been created for a video hosting website. However, I wanted to make it work with XML as well as JSON.

Phil Haack creates something called a JSON value provider, so I followed his example and created an XML value provider. I've used it on two projects now and it's worked a treat. I thought I'd share it with the world in the hope that it will be useful to others.

Source code

XML Value Provider (C# source)

To get this working in your project you'll need to follow Phil Haack's instructions for his JSON Value Provider.

If anyone has any suggested improvements to the code, then I'd love to hear them.

Update - January 2013

This code has now been updated to stop it being vulnerable to an XML Bomb DOS Attack. We all know that you shouldn't trust anything sent by the user, but less of us know that XmlReader has a clever feature for expanding entities and that this feature presents a nice attack vector. It's very easy to fix. You just need to provide a setting that prohibits DTD Processing. This probably should be the standard setting, but as it isn't, you need to know to turn if off. If you do need this feature then read the article for details on how to use it and still keep your site safe.

If you're using an early version of this code, you should update it to this version.

Using a Custom Model Binder

If your model object needs to use XML attributes then you may be better off using a custom XML model binder instead.

No Comments

  • Richard said

    I've been meaning to add licencing info to my code samples for a while.

    I like to licence code samples like this under the MIT licence because it's nice and simple. Lets you do whatever you like with it, but also makes it clear that I accept no responsibility for how the code functions in your system.

    So this code is licenced under the MIT licence.

    I also need to point out that the code is based on samples by Phil Haack on his blog which is licenced under creative commons and allows remixing and commercial use.

  • John said

    One inherent limitation it seems to this is you can't use xmlattribute overrides as the valueprovider doesn't know they exist and there's no good way to pass in expected object types..

    Any thoughts?

  • Richard said

    @John if you want the binding to be aware of xml attributes then using a value provider might not be the best method. You'll probably have to write your own custom model binder.

Comments have been disabled for this content.