title: Web API Conditional Serialization of properties at runtime
body: <p>I am looking at building an API using WebAPI in ASP.Net.</p>
  
  <p>I have a requirement to conditionally exclude properties from the XML or JSON based on some custom logic at <strong><code>RunTime</code> and not <code>Compile Time</code>.</strong></p>
  
  <p>I have to remove the xml or json from the response, it is no good just including the tags with a null or empty value.</p>
  
  <p>I have tried various approaches, none of which I seem to be able to get to work.</p>
  
  <p>I have tried the following</p>
  
  <p><strong>Delegating Handler</strong> <a href="https://stackoverflow.com/questions/16172076/contextual-serialization-from-webapi-endpoint-based-on-permissions">from here</a></p>
  
  <pre><code>public class ResponseDataFilterHandler : DelegatingHandler
  {
      protected override System.Threading.Tasks.Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
      {
          return base.SendAsync(request, cancellationToken)
              .ContinueWith(task =&gt;
              {
                  var response = task.Result;
  
                  //Manipulate content here
                  var content = response.Content as ObjectContent;
                  if (content != null &amp;&amp; content.Value != null)
                  {
  
                  }
  
                  //Or replace the content
                  //response.Content = new ObjectContent(typeof(object), new object(), new MyFormatter());
  
                  return response;
              });
      }
  
  
  }
  </code></pre>
  
  <p>Sure I can null properties out here, but they still appear in the response.</p>
  
  <p><strong>DataContractSurrogate</strong> <a href="http://www.codeproject.com/Articles/417168/Conditional-WCF-DataContract-Serialization-Using" rel="nofollow noreferrer">similar to this</a></p>
  
  <pre><code> public class MySurrogate: IDataContractSurrogate
  {
      public object GetCustomDataToExport(Type clrType, Type dataContractType)
      {
          return null;
      }
  
      public object GetCustomDataToExport(System.Reflection.MemberInfo memberInfo, Type dataContractType)
      {
          return null;
      }
  
      public Type GetDataContractType(Type type)
      {
          return null;
      }
  
      public object GetDeserializedObject(object obj, Type targetType)
      {
          return null;
      }
  
      public void GetKnownCustomDataTypes(System.Collections.ObjectModel.Collection&lt;Type&gt; customDataTypes)
      {
  
      }
  
      public object GetObjectToSerialize(object obj, Type targetType)
      {
          if (obj == null) return null;
  
          var type = obj.GetType();
          type.GetProperties().ToList()
            .ForEach(prop =&gt;
            {
                try
                {
                    var attr = prop.GetCustomAttributes(typeof(ConditionalDataMemberAttribute), false);
                    if (attr.Any())
                    {
                        var proptype = prop.PropertyType;
                        //Set the property value to its default value
                        prop.GetSetMethod().Invoke(obj,
                                                   new[] { proptype.IsValueType ? Activator.CreateInstance(proptype) : null });
                    }
                }
                catch { }
            });
  
  
          return obj;
  
      }
  
      public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
      {
          return null;
      }
  
      public System.CodeDom.CodeTypeDeclaration ProcessImportedType(System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit)
      {
          return null;
      }
  }
  </code></pre>
  
  <p>Again, I can just null the properties out, I cannot remove the xml or json from the output.</p>
  
  <p>I have an idea where I can dynamically compile a specific class with the required attributes then use the DataContractSurrogate to swap out the original instance with an instance of my new dynamic compiled class - but I don't like it.</p>
  
  <p>Ive tried looking at <code>DataContractSerializer</code> but it is sealed so I cant derive from it - i've also looked to decompile it and make some changes but again it uses internal classes such as <code>DataContract</code> - I feel I need to hook into the serialization but I don't know how to ?</p>