I have an ORM (NHibernate) that maps to POCOs that will be returned to ApiControllers. I understand that JSON.NET allows me to put conditional serialization methods (ShouldSerialize *) on my models; however, these models and their methods do not know anything about their environment and should not. What I would like to do is conditionally serialize the model or one or more of its properties based on the user's role when they entered my site. I can conceptually understand how this can be done, but I was lost on the one hand. Here's a sample model:
public class SomeModel { public string SomeProperty { get; set; } [Sensitive] public string SomeOtherProperty { get; set; } }
I would like to be able to put a property attribute so that it designates it as “Sensitive”. Then in my WebApi, when it serializes it for output, I would like it to check the model for this attribute, and if it exists, it should check the user role. If the user is in the specified role, the serializer must serialize the attribute, otherwise it either disguises it or simply does not serialize it. So do I have to write my own custom formatter to handle this, or is there a way to connect to the built-in to perform this check? Or am I too limited in my thoughts, and is there another way to handle this?
I thought that the other way this could be handled would be at the ORM level, but could not find good examples on the Internet.
Very valuable!
EDIT: here I found another similar question: Contextual serialization from a WebApi endpoint based on permissions but there was no solution. In addition, I do not like the idea of installing role-based access in models through attributes. I believe this should be handled in a web application.
c # serialization asp.net-web-api nhibernate sensitive-data
Zach
source share