How do I serialize an IdentityUser reference in Web API 2.2?

asp.net-identity asp.net-web-api2 c# entity-framework-6 serialization

Question

Endpoints are provided for managing user registration, authentication, and authorisation in the Visual Studio "Web API" project template. However, in a production application, users will often also be linked to other Entities, such as:

public class Post {
  public Post() {};
  public int Id { get; set; }
  public ApplicationUser User { get; set; }
}

When this occurs, theApplicationUser (which is descended fromIdentityUser ) is not serializable. If you try to do that, you'll get an error like this:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.

Similar concerns regarding the suggestion that a DTO be passed in place of theApplicationUser object. But that looks like a lot of developer work. Is serialization not possible?ApplicationUser directly?

1
1
3/8/2020 8:44:18 PM

Accepted Answer

Naturally, there are houses for sale onIdentityUser which shouldn't be made available to other people in the public, likePasswordHash . Others, likeEmail and PhoneNumber Depending on your API's authentication settings, it can go against user expectations for privacy. As a result, it is important to carefully consider which attributes are disclosed and which are not. Utilizing a DTO resolves these problems.

Having stated that, there is no reason why youIdentityUser adding the class to be serializedDataContractAttribute to the class you inherited:

[DataContract] 
public class ApplicationUser : IdentityUser {
  //...
}

Then, using the explicit include method, you can expose whatever custom attributes you want.DataMemberAttribute :

[DataMember]
public string TwitterHandle { get; set; }

If you want to expose those who areUserIdentity in order to override them:

[DataMember]
public override string UserName {
  get {
    return base.UserName;
  }
  set {
    base.UserName = value;
  }
}

Finally, it's important to remember that anyone with access to the endpoint will also have access to these characteristics. Wrapping the object with a DTO will give you more precise control over who can view what.

3
5/2/2015 12:03:15 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow