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();
哇,令人尷尬。謝謝。 – Kyle 2012-03-22 15:34:55
不是很尷尬。一個常見的錯誤 - 我也很難學會。 – Aliostad 2012-03-22 15:37:00
我一直在努力爭取最佳實踐。我曾經在會話中緩存Principal對象,但這似乎也是一個糟糕的主意。我對錶單身份驗證相當陌生。最好的方法是什麼? – Kyle 2012-03-22 15:37:40