title: NewtonSoft json Contract Resolver with MVC 4.0 Web Api not producing the output as expected
body: <p>I am trying to create a conditional ContractResolver so that I can control the serialization differently depending on the web request/controller action.  </p>
  
  <p>For example in my User Controller I want to serialize all properties of my User but some of the related objects I might only serialize the primitive types.  But if I went to my company controller I want to serialize all the properties of the company but maybe only the primitive ones of the user (because of this I don't want to use dataannotations or shouldserialize functions.  </p>
  
  <p>So looking at the custom ContractResolver page i created my own. 
  <a href="http://james.newtonking.com/projects/json/help/index.html?topic=html/ContractResolver.htm" rel="nofollow">http://james.newtonking.com/projects/json/help/index.html?topic=html/ContractResolver.htm</a></p>
  
  <p>It looks like this</p>
  
  <pre><code>public class IgnoreListContractResolver : DefaultContractResolver
  {
      private readonly Dictionary&lt;string, List&lt;string&gt;&gt; IgnoreList;
  
      public IgnoreListContractResolver(Dictionary&lt;string, List&lt;string&gt;&gt; i)
      {
          IgnoreList = i;
      }
  
      protected override IList&lt;JsonProperty&gt; CreateProperties(Type type, MemberSerialization memberSerialization)
      {
          List&lt;JsonProperty&gt; properties = base.CreateProperties(type, memberSerialization).ToList();
  
          if(IgnoreList.ContainsKey(type.Name))
          {
              properties.RemoveAll(x =&gt; IgnoreList[type.Name].Contains(x.PropertyName));                
          }
          return properties;
      }
  }
  </code></pre>
  
  <p>And then in my web api controller action for GetUsers i do this</p>
  
  <pre><code>public dynamic GetUsers()
  {
      List&lt;User&gt; Users = db.Users.ToList();
      List&lt;string&gt; RoleList = new List&lt;string&gt;();
      RoleList.Add("UsersInRole");
      List&lt;string&gt; CompanyList = new List&lt;string&gt;();
      CompanyList.Add("CompanyAccesses");
      CompanyList.Add("ArchivedMemberships");
      CompanyList.Add("AddCodes");
  
      Dictionary&lt;string, List&lt;string&gt;&gt; IgnoreList = new Dictionary&lt;string, List&lt;string&gt;&gt;();
      IgnoreList.Add("Role", RoleList);
      IgnoreList.Add("Company", CompanyList);
      GlobalConfiguration
              .Configuration
              .Formatters.JsonFormatter
              .SerializerSettings
              .ContractResolver = new IgnoreListContractResolver(IgnoreList);
  
      return new { List = Users, Status = "Success" };
  }
  </code></pre>
  
  <p>So when debugging this I see my contract resolver run and it returns the correct properties but the Json returned to the browser still contains entries for the properties I removed from the list.  </p>
  
  <p>Any ideas what I am missing or how I can step into the Json serialization step in webapi controllers.</p>
  
  <hr>
  
  <p>*<strong><em>UPDATE</em>**</strong>
  I should add that this is in an MVC4 project that has both MVC controllers and webapi controllers.  The User, Company, and Role objects are objects (created by code first) that get loaded from EF5.  The controller in question is a web api controller.  Not sure why this matters but I tried this in a clean WebApi project (and without EF5) instead of an MVC project and it worked as expected.   Does that help identify where the problem might be?  </p>
  
  <p>Thanks</p>
  
  <hr>
  
  <p><em><strong></em>*UPDATE 2*<em>*</em></strong>
  In the same MVC4 project I created an extension method for the Object class which is called ToJson.  It uses Newtonsoft.Json.JsonSerializer to serialize my entities.  Its this simple. </p>
  
  <pre><code>public static string ToJson(this object o, Dictionary&lt;string, List&lt;string&gt;&gt; IgnoreList)
  {
      JsonSerializer js = JsonSerializer.Create(new Newtonsoft.Json.JsonSerializerSettings()
      {
          Formatting = Formatting.Indented,
          DateTimeZoneHandling = DateTimeZoneHandling.Utc,
          ContractResolver = new IgnoreListContractResolver(IgnoreList),
          ReferenceLoopHandling = ReferenceLoopHandling.Ignore  
      });
  
      js.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
  
      var jw = new StringWriter();
      js.Serialize(jw, o);
      return jw.ToString();
  
  }
  </code></pre>
  
  <p>And then in an MVC action i create a json string like this. </p>
  
  <pre><code>model.jsonUserList = db.Users.ToList().ToJson(IgnoreList);
  </code></pre>
  
  <p>Where the ignore list is created exactly like my previous post.  Again I see the contract resolver run and correctly limit the properties list but the output json string still contains everything (including the properties I removed from the list).  Does this help?  I must be doing something wrong and now it seems like it isn't the MVC or web api framework.  Could this have anything to do with EF interactions/ proxies /etc.  Any ideas would be much appreciated.  </p>
  
  <p>Thanks</p>
  
  <hr>
  
  <p>*<strong><em>UPDATE 3</em>***</strong></p>
  
  <p>Process of elimination and a little more thorough debugging made me realize that EF 5 dynamic proxies were messing up my serialization and ContractResolver check for the type name match.  So here is my updated IgnoreListContractResolver.  <strong>At this point I am just looking for opinions on better ways or if I am doing something terrible.</strong>  I know this is jumping through a lot of hoops just to use my EF objects directly instead of DTOs but in the end I am finding this solution is really flexible. </p>
  
  <pre><code>public class IgnoreListContractResolver : CamelCasePropertyNamesContractResolver
  {
      private readonly Dictionary&lt;string, List&lt;string&gt;&gt; IgnoreList;
  
      public IgnoreListContractResolver(Dictionary&lt;string, List&lt;string&gt;&gt; i)
      {
          IgnoreList = i;
      }
  
      protected override IList&lt;JsonProperty&gt; CreateProperties(Type type, MemberSerialization memberSerialization)
      {
          List&lt;JsonProperty&gt; properties = base.CreateProperties(type, memberSerialization).ToList();
  
          string typename = type.Name;
          if(type.FullName.Contains("System.Data.Entity.DynamicProxies.")) {
              typename = type.FullName.Replace("System.Data.Entity.DynamicProxies.", "");
              typename = typename.Remove(typename.IndexOf('_'));
          }
  
          if (IgnoreList.ContainsKey(typename))
          {
              //remove anything in the ignore list and ignore case because we are using camel case for json
              properties.RemoveAll(x =&gt; IgnoreList[typename].Contains(x.PropertyName, StringComparer.CurrentCultureIgnoreCase));
          }
          return properties;
      }
  } 
  </code></pre>