title: ASP.NET WebAPI Conditional Serialization based on User Role
body: <p>I have an ORM (NHibernate) that maps to POCOs which will be returned in ApiControllers.  I realize that  JSON.NET allows me to put conditional serialization methods (ShouldSerialize*) on my models; however, these models and their methods have no knowledge of anything about their environment, nor should they.  What I would like to do is conditionally serialize a model or one or more of its properties based on the user's role when they're signed into my website.  I can conceptually perceive how this can be done but I'm lost at one part.  Here's a sample model:</p>
  
  <pre><code>public class SomeModel
  {
      public string SomeProperty { get; set; }
  
      [Sensitive]
      public string SomeOtherProperty { get; set; }
  }
  </code></pre>
  
  <p>I would like to be able to put an attribute on a property to flag it as "Sensitive".  Then in my WebApi when it is serializing it for output, I would like for it to check the model for this attribute and, if it exists, it should check the user's role.  If the user is in the specified role, then the serializer should serialize the attribute, otherwise it will either mask it out or simply not serialize it.  So would I have to write my own custom formatter to handle this or is there a way to hook into the built-in ones to perform this check?  Or am I too limited in my thinking, and there's another way to handle this?</p>
  
  <p>I did think that another way this could be handled would be at the ORM level but couldn't find good examples online.</p>
  
  <p>Much appreciated!</p>
  
  <p>EDIT:  I did find another similar question here:
  <a href="https://stackoverflow.com/questions/16172076/contextual-serialization-from-webapi-endpoint-based-on-permissions">Contextual serialization from WebApi endpoint based on permissions</a>
  but there was no solution. Also, I don't like the idea of setting role-based access in the models via attributes.  I believe that should be handled in the web application.</p>