title: Modifying how JSON.Net handles serializing a class, without direct access to JSON.Net
body: <p>I am working on a very old, but very large and very active <strong>ASP.NET webforms</strong> site, that uses a <a href="https://docs.microsoft.com/en-us/previous-versions/aspnet/ms178587(v=vs.100)" rel="nofollow noreferrer">custom Session State provider</a> that relies on <strong>JSON.Net</strong>.</p>
  <p>One side effect of this is that objects that are based on plain, non-generic <code>IEnumerable</code> can be put in <code>Session</code>, but not retrieved from it. This is a <strong>JSON.Net</strong> limitation (an exception will be thrown if you try.)</p>
  <p>Stripped of its details, my situation is this:  I need to stash an object in <code>Session</code>, of a third-party-provided, sealed class, for which I don't have the source code, that's based on <code>IEnumerable</code>. (We'll call it <code>VendorClassA</code>.)</p>
  <p>And: I need to be able to get it out again.</p>
  <p><strong>And that's what doesn't work.</strong></p>
  <p>I have tried mapping an instance of <code>VendorClassA</code> to something else, stashing <em>that</em> in <code>Session</code>, and then converting it back. That works quite well.</p>
  <p>But it turns out that there's one place -- within the third-party, inaccessible code -- where an instance of <code>VendorClassA</code> is retrieved from <code>Session</code>, and if it can't be retrieved, or if the retrieved object can't be cast to <code>VendorClassA</code>, a fatal exception is thrown.</p>
  <pre><code>VendorClassA value = (VendorClassA) HttpContext.Current.Session[&quot;key&quot;];
  </code></pre>
  <p>I can't change that code (third-party, no source code, etc.)</p>
  <p>And I can't modify the code that does the actual <strong>JSON.Net</strong> serialization, to change which methods are invoked, or how, because that's deep in the custom session state provider. Which I have no access to, both programmatically and organizationally.</p>
  <p><strong>So, my question:</strong></p>
  <p>Is there any way I can affect how <strong>JSON.Net</strong> handles this <em>specific</em> class's serialization, given that I can't change any of the following:</p>
  <ul>
  <li>That the object I put into Session State needs to be an instance of <code>VendorClassA</code>, or at least castable to it, because code I can't change will try to cast it to <code>VendorClassA</code>.</li>
  <li>The attributes on <code>VendorClassA</code></li>
  <li>That it's based on plain, non-generic <code>IEnumerable</code>.</li>
  <li>That <code>VendorClassA</code> is sealed</li>
  <li>How the <strong>JSON.Net</strong> serialization routines are called and what parameters or overloads they use.</li>
  </ul>
  <p>Perhaps there's some way to introduce a custom contract for <code>VendorClassA</code>, that would be globally applicable, but which could be introduced from a distance?</p>
  <p>Is there a better way?</p>