title: Serializing a Request Object using JSON
body: <p>I'm currently working on a proof-of-concept and ran into an issue involving using JSON to serialize an HttpRequest.</p>
  
  <p><strong>Background</strong></p>
  
  <p>I originally thought that I would be able to easily accomplish it using the <a href="http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode%28v=vs.111%29.aspx" rel="noreferrer">JSON.Encode()</a> method as seen below : </p>
  
  <pre><code>JSON.Encode(HttpContext.Request)
  </code></pre>
  
  <p>However, I quickly found that this causes all sorts of circular references to be thrown (<em>primarily due to the actual structure and complexity of the Request object</em>). These only occur when actually encountering properties that do contain a circular reference, as I have previously used the following code to grab just specific elements that I need : </p>
  
  <pre><code>JSON.Encode(new {HttpContext.Request.Cookies,HttpContext.Request.Headers, ... });
  </code></pre>
  
  <p>which works just fine.</p>
  
  <p>I'm just curious if there is a better method of handling this (<em>or what the best method of handling it may be</em>). I'll detail a few of the approaches that I have taken so far below to possibly find any areas that I may have gone wrong.</p>
  
  <p><strong>Previous Approaches</strong></p>
  
  <ul>
  <li><p>Using Reflection to iterate through each of the properties within the
  Request and attempting to construct a JSON string
  "property-by-property". (<em>This failed when encountering a circular
  reference</em>)</p></li>
  <li><p>Attempting to store each of the Properties within a Dictionary object and then using JSON to serialize the entire Dictionary (<em>in hopes that it would "flatten" the object out and make it easier to serialize</em>)</p></li>
  <li><p>Using the <a href="http://james.newtonking.com/projects/json-net.aspx" rel="noreferrer">JSON.NET library</a> and trying to serialize it through the JsonConvert.SerializeObject() method (<em>I have tried to pass in several additional settings to avoid a circular reference, but haven't had any luck</em>)</p></li>
  </ul>
  
  <p>My latest approach (<em>using the JSON.NET library</em>) I thought would come close to working, however I encountered an error that involved a "Timeout" property on Stream objects within the Request.</p>
  
  <p>I'm not opposed to simply avoiding serializing Stream objects and Circular References. I'm just trying to grab as much of the Request object as possible while avoiding any of these types of mishaps.</p>