title: .Net Core Api - Custom JSON Resolver based on Request Values
body: <p>I'm looking to have all <code>OkObjectResult</code> responses coming out of my api get run through a custom JSON resolver that I have.  The resolver relies on some request-specific data - namely, the user's roles.  It's effectively like the Authorize attribute on a controller, but for data transfer objects passed from the API to the UI.</p>
  
  <p>I can add the resolver in Configure Services via AddJsonOptions, but it doesn't have access to that user info there.</p>
  
  <p>How can I pass values that are based on the request to this resolver? Am I looking at some sort of custom middleware, or something else?</p>
  
  <p>As a sample, if I have an object with some custom attribute decorators, like so:</p>
  
  <pre><code>public class TestObject
  {
      public String Field1 =&gt; "NoRestrictions";
      [RequireRoleView("Admin")]
      public String Field2 =&gt; "ViewRequiresAdmin";
  }
  </code></pre>
  
  <p>And call my custom serializer with different roles, like so:</p>
  
  <pre><code>var test = new TestObject();
  var userRoles = GetRoles(); // "User" for the sake of this example
  var outputJson = JsonConvert.SerializeObject(test, 
                      new JsonSerializerSettings { 
                          ContractResolver = new MyCustomResolver(userRoles) 
                      });
  </code></pre>
  
  <p>Then the output JSON will skip anything the user can't access, like so:</p>
  
  <pre><code>{
      "Field1":"NoRestrictions",
      // Note the absence of Field2, since it has [RequireRoleView("Admin")]
  }
  </code></pre>