序列化自定义主体对象

时间:2012-03-22 15:27:46

标签: .net serialization forms-authentication datacontractserializer

我有一个自定义主体对象,我希望能够序列化,以便我可以将它存储在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
}

这是我试图运行的代码,以便将其全部集中起来:

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 个答案:

答案 0 :(得分:1)

你错过了一行:

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

请记住serializer写入流,StreamReader从当前位置开始,即流的末尾。

另外,序列化IPrincipalIIdentity看起来不是一件好事。原因是它们代表易变状态,可随时更改(例如,序列化后撤销权限)。