title: Serialization for Azure Redis Caching
body: <p>I have an ASP.Net app hosted on Azure App Service. </p>
  
  <p>I understood that the default "<strong>InProc</strong>" session caching doesn't work in Azure.</p>
  
  <p>Was looking for workaround, and came across Redis, which I have enabled in Azure and set following in the config file</p>
  
  <pre><code> &lt;sessionState mode="Custom" customProvider="RedisStateStore"&gt;
    &lt;providers&gt;
      &lt;add name="RedisStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" 
           host="xxx.redis.cache.windows.net:6380" accessKey="xxx=" ssl="true"
           redisSerializerType="MyApp.Net.Helper.JsonSerializer,MyApp.Net"
           /&gt;
    &lt;/providers&gt;
  &lt;/sessionState&gt;&lt;/system.web&gt;
  </code></pre>
  
  <p>By default, I started getting <strong><em>assembly not serialized</em></strong> error for some forms. Since I'm using EF with 50 tables, not sure which one was to be serialized and it becomes tedious.</p>
  
  <p>Hence enabled a custom handler handler here :</p>
  
  <pre><code>    public class JsonSerializer : Microsoft.Web.Redis.ISerializer
  {
      private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All,
          ReferenceLoopHandling = ReferenceLoopHandling.Ignore, PreserveReferencesHandling = PreserveReferencesHandling.Objects,
      Error = (serializer, err) =&gt; {
          err.ErrorContext.Handled = true;
      }
      };
  
  public byte[] Serialize(object data)
      {
          return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data, Settings));
      }
  
      public object Deserialize(byte[] data)
      {
          return data == null ? null : JsonConvert.DeserializeObject(Encoding.UTF8.GetString(data), Settings);
      }
  }
  </code></pre>
  
  <p>But this was like serializing every object there and I feel its actually slowing down the system further. And then it was failing on some object arrays, like <a href="https://www.screencast.com/t/3YahfWhFeUP" rel="nofollow noreferrer" title="following">following</a></p>
  
  <p>If I ignore the error like the code above (which I know is bad practice), sometimes I come across <strong><em>System.OutOfMemoryException</em></strong> exception.</p>
  
  <p>Any advise appreciated here.</p>