0

我有一个自定义主体对象,我希望能够序列化,以便我可以将其存储在FormsAuthentication cookie的Userdata中。我试图使用DataContractJsonSerializer来做到这一点,但当序列化发生时,我只是得到一个空字符串(没有例外)。序列化自定义主体对象

[DataContract] 
public class MyPrincipal : IPrincipal 
{ 
    private readonly MyIdentity _identity; 

    public MyPrincipal(MyIdentity identity) 
    { 
     _identity = identity; 
    } 

    [DataMember] 
    public IIdentity Identity 
    { 
     get { return _identity; } 
     set { } 
    } 

    public bool IsInRole(string role) 
    { 
     return _identity.AuthGroups.Contains(role, StringComparer.OrdinalIgnoreCase); 
    } 

    public bool IsInRole(string[] roles) 
    { 
     return roles.Any(IsInRole); 
    } 
} 

[DataContract] 
public class MyIdentity : IIdentity 
{ 
    private readonly MyCustomData _customData; 

    public MyIdentity(MyCustomData customData) 
    { 
     _customData = customData; 
    } 

    #region IIdentity properties 

    [DataMember] 
    public string Name 
    { 
     get { return Username; } 
     set {} 
    } 

    [DataMember] 
    public string AuthenticationType 
    { 
     get { return "Forms"; } 
     set {} 
    } 

    [DataMember] 
    public bool IsAuthenticated 
    { 
     get { return true; } 
     set { } 
    } 

    #endregion 

    #region custom properties 

    [DataMember] 
    public string FirstName 
    { 
     get { return _customData.FirstName; } 
     set { } 
    } 
    [DataMember] 
    public string LastName 
    { 
     get { return _customData.LastName; } 
     set { } 
    } 
    [DataMember] 
    public string RedwoodID 
    { 
     get { return _customData.CedarnetRedwoodID; } 
     set { } 
    } 
    [DataMember] 
    public string Username 
    { 
     get { return _customData.NetworkLogin; } 
     set { } 
    } 
    [DataMember] 
    public string CuwasTicket 
    { 
     get { return _customData.CuwasTicket; } 
     set { } 
    } 
    [DataMember] 
    public List<string> AuthGroups 
    { 
     get { return _customData.GroupMembership; } 
     set { } 
    } 

    #endregion 
} 

这里就是我试图运行到seralize它所有代码:

var serializer = new DataContractJsonSerializer(typeof(MyPrincipal), new List<Type> {typeof(MyPrincipal), typeof(MyIdentity)}); 
var responseStream = new MemoryStream(); 
serializer.WriteObject(responseStream, user); 
string serializedValue = new StreamReader(responseStream).ReadToEnd(); 

回答

1

你错过了一个行:

serializer.WriteObject(responseStream, user); 
responseStream.Position = 0; // This!! 
string serializedValue = new StreamReader(responseStream).ReadToEnd(); 

记住serializer写入流和StreamReader开始从当前位置流这是流的结束。

在另一张纸条上,系列化IPrincipalIIdentity看起来不是一件好事。原因是它们代表了一种随时可能改变的易失性状态(例如序列化后撤销权限)。

+0

哇,令人尴尬。谢谢。 – Kyle 2012-03-22 15:34:55

+0

不是很尴尬。一个常见的错误 - 我也很难学会。 – Aliostad 2012-03-22 15:37:00

+0

我一直在努力争取最佳实践。我曾经在会话中缓存Principal对象,但这似乎也是一个糟糕的主意。我对表单身份验证相当陌生。最好的方法是什么? – Kyle 2012-03-22 15:37:40