Reputation: 2261
I would like to be able to expose a list of users using WebAPI 2. However since I am using the new Asp.Net Authentication framework in MVC5, I can't seem to find a way to only mark specific fields as DataMembers
.
Heres what I have:
[DataContract]
public class ApplicationUser : IdentityUser {
public Nullable<DateTime> birthday { get; set; }
[DataMember]
public int tolerance { get; set; }
[DataMember]
public string twitter { get; set; }
}
However, that doesn't seem to work because IdentityUser
doesn't have the [DataContract]
attribute. I've tried creating a custom IdentityUser
, but I haven't been able to build after creating a custom copy of IdentityUser
.
Any tips or work arounds here? I'd prefer not to have to create a ViewModel, unless that's the current best practice.
Upvotes: 2
Views: 1540
Reputation: 4619
I know this is an old question and I stumbled upon it when I was trying to achieve the same thing. Here's what I ended up doing. You could override your properties and mark them as [JsonIgnore] so that they won't get serialised automatically.
public class ApplicationUser : IdentityUser
{
public UserType UserType { get; set; }
[JsonIgnore]
public override string PasswordHash
{
get { return base.PasswordHash; }
set { base.PasswordHash = value; }
}
}
Upvotes: 3
Reputation: 3908
What formatter do you want to use? I don't see any issue with default Json formatter. But for xml serializer, it requires base class to be DataContract as well.
View model is always the best practice here, although most of the samples for web api are using data entity for simplicity. The two models are separate of concerns. View model represents the contract of your api and the data model represents your domain concept. Combining two models into one can impact your design decision or even more seriously, can cause security issues. Using data entity may expose unexpected data to user. For example, different formatters have different rules to control the exposure of model. JsonIgnore doesn't work in xml formatter. It will be more complicated if you have custom formatter. Especially for the identity user entity, which has many sensitive properties like pasword hash, security stamp. I won't recommend you expose it to public.
BTW, there is many mapper tools that can help to simplify the mapping from domain model to view model. You may need them: http://www.nuget.org/packages?q=mapper
Upvotes: 1
Reputation: 28200
You probably should just send a different object with the user info you need as opposed to serializing the user object.
Upvotes: 3