WEB API and Serializable

10/19/20161 Min Read — In ASP.NET, WEB API

Recently I was working on a solution that needed to make use of Redis to cache expensive calculated results to increase performance. We added the dependency to Redis and marked the desired classes with the Serializable attribute to satisfy our cache layer requirement. However, an unintended consequence was encountered when attempting to hit our API.

Instead of receiving the expected json result we received all properties prepended with k_BackingField which was failing our consuming services.

Using DataContract and DataMember attributes

The first and most tedius was to add a DataContract and DataMember to the class.

public class MyClass{
public string MyProp1 { get; set; }

Albeit this approach works it’s extremely taxing on large code bases simply to support Serializable Classes.

Ignoring The Serializable Attribute In Global.asax

We ended up finding a solution that allows you to update the Application_Start method of the Global.asax file of your WEB API to ignore the serializable attribute and emit out your objects as they previously were emitted prior to adding the Serializable attribute.

protected void Application_Start()
var serializerSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
var contractResolver = (DefaultContractResolver)serializerSettings.ContractResolver;
contractResolver.IgnoreSerializableAttribute = true;