ASP.NET WebAPI and k_BackingField in your JSON

If you’ve ever written AJAX-accessible WCF services and needed to return structured data to the client, it’s likely that you’ll have seen a fairly simple model object with automatic properties (i.e. get and set specified but their implementation left absent) received by the client with funky field names, all prefixed by k_BackingField. It doesn’t take much Googling to suss that marking your model object with a [DataContract] attribute and properties with [DataMember] attributes fixes things up and lets the serialiser make the correct field naming decisions for these properties.

You can get into a similar situation using the ApiController of the ASP.NET WebAPI, where you have the following setup:

  • A model class with one or more auto properties
  • A controller action method that returns an instance of the model, or a collection of the model
  • The model class is marked as [Serializable] to allow it to be stored in out-of-proc session state

That last part’s crucial – if you want to store an object in out-of-process session state (for example, using the session service or a SQL database then it needs to be marked as [Serializable] for persistence and re-hydration. The problem is that while an un-attributed model will be automatically serialised to nicely-named JSON fields, by attaching a [Serializable] attribute we end up with k_BackingField once again. Bugger.

I’ve found three options, with the last suggesting that this will not be a problem in future versions of the framework.

The first is to have a second model type used only for storage in session state, marked with Serializable as appropriate and perhaps with an operator to cast between it and the one to be returned to the client via WebAPI calls.

The second is to mark up your model class with a [DataContract] attribute, and then mark up the properties that need serialisation to JSON with [DataMember] attributes.

The last is to replace the default formatter with a Newtonsoft Json.NET one – which it seems will in the future be the default JSON formatter anyway. This formatter doesn’t render the backing field names into the resultant JSON, but instead just uses the property names – it also doesn’t suffer from the many limitations of the standard DataContractJsonSerializer.

So it’s a pretty rare situation that’s likely to go away on its own when WebAPI goes RTM, but at least it can be worked-around until then with relative ease.

Leave a Reply

Your email address will not be published. Required fields are marked *