【发布时间】:2012-03-22 15:27:46
【问题描述】:
我有一个自定义主体对象,我希望能够对其进行序列化,以便可以将其存储在 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();
【问题讨论】:
标签: .net serialization forms-authentication datacontractserializer