问题描述
Visual StudioWeb API"项目模板包括用于处理用户注册、身份验证和授权的端点.然而,在生产应用程序中,用户通常也会与其他实体相关联,例如:
The Visual Studio "Web API" project template includes endpoints for handling registration, authentication, and authorization of users. In a production application, however, users will typically be associated with other Entities as well, such as:
public class Post {
public Post() {};
public int Id { get; set; }
public ApplicationUser User { get; set; }
}
在这些情况下,ApplicationUser
类(派生自 IdentityUser
)无法序列化.尝试这样做会产生类似于以下内容的错误:
In these scenarios, the ApplicationUser
class (which is derived from IdentityUser
) cannot be serialized. Attempting to do so will yield an error similar to:
ObjectContent`1"类型未能序列化内容类型application/json;"的响应正文;charset=utf-8'.
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.
我在其他地方看到过类似的问题,建议传递 DTO 而不是 ApplicationUser
对象.然而,这似乎是很多开发人员的开销.有没有办法直接序列化ApplicationUser
?
I've seen similar issues raised elsewhere with the recommendation to pass a DTO instead of the ApplicationUser
object. That seems like a lot of developer overhead, however. Is there not a way to serialize ApplicationUser
directly?
推荐答案
显然,IdentityUser
上有一些属性不应该公开给其他用户,例如 PasswordHash代码>.其他的,例如
Email
和 PhoneNumber
可能会违反用户隐私期望,具体取决于您的 API 的身份验证设置.因此,应该仔细评估哪些属性是暴露的和没有暴露的.使用 DTO 可以解决这些问题.
Obviously, there are properties available on IdentityUser
which should not be publicly exposed to other users, such as PasswordHash
. Others, such as Email
and PhoneNumber
may violate user privacy expectations depending on your API's authentication settings. As such, which properties are and are not exposed should be carefully evaluated. Using a DTO addresses these issues.
也就是说,没有理由不能通过将 DataContractAttribute
添加到继承的类来配置要序列化的 IdentityUser
类:
That said, there is no reason you can't configure the IdentityUser
class to be serialized by adding the DataContractAttribute
to your inherited class:
[DataContract]
public class ApplicationUser : IdentityUser {
//...
}
然后您可以使用 DataMemberAttribute
显式包含您希望公开的任何自定义属性:
You may then explicitly include any custom properties you wish to expose using the DataMemberAttribute
:
[DataMember]
public string TwitterHandle { get; set; }
如果您希望公开 UserIdentity
的成员,则需要覆盖它们:
If you wish to expose members of UserIdentity
, you'll need to override them:
[DataMember]
public override string UserName {
get {
return base.UserName;
}
set {
base.UserName = value;
}
}
最后,值得注意的是,这些属性将与有权访问端点的任何人共享.如果您想更详细地控制谁可以看到什么,那么将对象包装在 DTO 中即可.
Finally, it's worth noting that these properties will be shared with anyone who has access to the endpoint. If you want more detailed control over who sees what then wrapping the object in a DTO will provide that.
这篇关于如何在 Web API 2.2 中序列化 IdentityUser 引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!