title: Dynamically select attributes to serialize in JSON response in asp.net core
body: <p>I have a controller like this:</p>
  
  <pre><code>using Microsoft.AspNetCore.Mvc;
  
  public class Person {
      public string FirstName { get; set; }
      public string LastName { get; set; }
  }
  
  [Route("api/[controller]")]
  public class ValuesController : Controller {
      [HttpGet]
      public IActionResult Get() {
          return new OkObjectResult(new[] {
              new Person { FirstName = "John", LastName = "Doe" }
          });
      }
  }
  </code></pre>
  
  <p>I would like to be able to specify the properties I want from the response in a asp.net core REST API.<br>
  For example, a <code>GET</code> to <code>api/values</code> should return an object with all its properties:</p>
  
  <pre><code>{
    "FirstName":"John",
    "LastName":"Doe"
  }
  </code></pre>
  
  <p>While, a <code>GET</code> to <code>api/values?fields=FirstName</code> should return only the FirstName property:     </p>
  
  <pre><code>{
    "FirstName":"John"
  }
  </code></pre>
  
  <p>I tried specifying a ContractResolver in my Startup class like this:</p>
  
  <pre><code>class QueryStringResolver : DefaultContractResolver {
      protected override IList&lt;JsonProperty&gt; CreateProperties(Type type, MemberSerialization memberSerialization) {
          HttpContextAccessor httpContextAccessor = new HttpContextAccessor();
          string fieldsQuery = httpContextAccessor.HttpContext.Request.Query["fields"];
          if (!string.IsNullOrEmpty(fieldsQuery)) {
              var fields = from f in fieldsQuery.Split(",", StringSplitOptions.RemoveEmptyEntries) select f.Trim().ToLowerInvariant();
              return base.CreateProperties(type, memberSerialization).Where(p =&gt; fields.Contains(p.PropertyName.ToLowerInvariant())).ToList();
          } else {
              return base.CreateProperties(type, memberSerialization);
          }
      }
  }
  
  public class Startup {
      public void ConfigureServices(IServiceCollection services) {
          services
              .AddMvc()
              .AddJsonOptions(options =&gt; {
                  options.SerializerSettings.ContractResolver = new QueryStringResolver();
              });
      }
      // rest of Startup class omitted...
  }
  </code></pre>
  
  <p>The problem is that the <code>CreateProperties</code> method is invoked only at the first request, and not for each request.</p>
  
  <p>Is there a way to specify which properties should be serialized at each request?</p>
  
  <p>Please note that <strong>I don't want to change the Get method implementation or the returned class definition</strong>, I would just like to act on the serialization, so that I can re-use the same query string parameter in several methods.</p>