How to include/exclude properties from a WEB API response based on a user's role using attributes? For example:
public class Employee
{
public string FullName { get; set;}
[DataMember(Role="SystemAdmin")] // included only for SystemAdmins
public string SSN { get; set; }
}
You can use conditional serialization depending on what serializer(s) you are using in web api.
If you are just returning JSON from Web API its simple - I use only the JSON serializer and this solution works for me. By default Web API uses JSON.Net for JSON serialization. You can add a ShouldSerialize method that returns a bool. In the should serialize you can test if the user IsInRole
public class Employee
{
public string Name { get; set; }
public string Manager { get; set; }
public bool ShouldSerializeManager()
{
// don't serialize the Manager property for anyone other than Bob..
return (Name == "Bob");
}
}
More details
The [JsonIgnore] attribute is all or nothing when using the JSON.Net Web API serialization.
Other serializers require different approaches...
The XmlSerializer also supports this but you have to enable it
config.Formatters.XmlFormatter.UseXmlSerializer = true;
The datacontract serializer is the default.
If using this you would have to add logic into the properties and omit them if null.. This can be a problem if you use the class elsewhere. The [IgnoreDataMember] attribute is all or nothing.
[DataContract]
public class Person
{
private string firstName;
[DataMember(IsRequired = false, EmitDefaultValue = false)]
public string FirstName
{
get
{
//Put here any condition for serializing
return string.IsNullOrWhiteSpace(firstName) ? null : firstName;
}
set
{
firstName = value;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With