I'm working on a Web API 2 based service, using Entity Framework 6 for persistence and ASP.NET Identity for authentication. I use the default IdentityUser implementation for Entity Framework.
Say I have an entity like this:
public class Example
{
[Key]
public string Id { get; set; }
public string Foo { get; set; }
public string Bar { get; set; }
public virtual IdentityUser OwningUser { get; set; }
}
And in my Web API controller, a HTTP GET request returns a record this way:
public async Task<Example> Get( string id )
{
var example = await _exampleRepository.FindByIdAsync( id );
return example;
}
This works just fine. However, a request would return JSON such as this:
{
id: "some id",
foo: "some foo",
bar: "some bar",
owningUser: {
claims: [],
logins: [],
roles: [
{
userId: "some user id",
roleId: "some role id"
}
],
securityStamp: "jadshgiuahsduigh",
passwordHash: "adsghasdjgiasdg",
email: "[email protected]",
emailConfirmed: false,
... snip ...
userName: "some user",
id: "some user id"
}
}
I don't want to return all that user data! What I'd like to do is to somehow intercept the JSON that's being generated and whitelist properties to include, so that in this case, the serialized IdentityUser object returned from the API would only include this:
owningUser: {
userName: "some user",
id: "some user id"
}
How can I achieve this? I don't want to truncate IdentityUser records across the board; this would have to be something I can opt in to on a controller action basis. Is this something that could be achieved with an action filter? And where in the pipeline would the interception need to take place? Ideally I'd want to have custom serialization for just the instances of IdentityUser in the object graph I'm returning from my controller action, rather than directly manipulating the finished JSON response. I'm running Web API as OWIN middleware if that's relevant.