C# ';Microsoft.AspNet.Identity.EntityFramework.IdentityUser';未标记为可序列化
我在一个系统中实现ASP.NET标识,该系统使用具有实体框架的用户模型进行身份验证,并在WebApp中通过会话进行控制(是的,它是一个传统的web表单系统),我们实现了,用标识的C# ';Microsoft.AspNet.Identity.EntityFramework.IdentityUser';未标记为可序列化,c#,asp.net,entity-framework,serialization,asp.net-identity,C#,Asp.net,Entity Framework,Serialization,Asp.net Identity,我在一个系统中实现ASP.NET标识,该系统使用具有实体框架的用户模型进行身份验证,并在WebApp中通过会话进行控制(是的,它是一个传统的web表单系统),我们实现了,用标识的应用程序用户替换了用户模型,一切正常 问题是,有一个通知系统,它基本上是通知和用户模型之间的多对多关系, 这些通知与系统的其余部分一起保存在SQL Server中,但也保存在缓存Redis中,以便更快地读取,并且需要序列化以便在其上写入。我们删除了用户模型,然后在通知模型中添加了应用程序用户的ICollection,反之
应用程序用户
替换了用户
模型,一切正常
问题是,有一个通知系统,它基本上是通知
和用户
模型之间的多对多关系,
这些通知与系统的其余部分一起保存在SQL Server中,但也保存在缓存Redis中,以便更快地读取,并且需要序列化以便在其上写入。我们删除了用户
模型,然后在通知
模型中添加了应用程序用户
的ICollection
,反之亦然-使两者之间建立关联
但是ApplicationUser
继承自IdentityUser
,甚至添加注释[Serializable]
我也得到了例外:
键入“Microsoft.AspNet.Identity.EntityFramework.Identity用户”
程序集“Microsoft.AspNet.Identity.EntityFramework,版本”=
2.0.0.0,区域性=中性,PublicKeyToken=31bf3856ad364e35'未标记为可序列化
我的问题是,有没有办法将其序列化?或者我必须创建另一个用户模型才能与通知模型关联
应用程序用户
型号
[Serializable]
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
this.Notificacoes = new List<Notificacao>();
}
public ClaimsIdentity GenerateUserIdentity(IdentityConfig.ApplicationUserManager manager)
{
var userIdentity = manager.CreateIdentity(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public Task<ClaimsIdentity> GenerateUserIdentityAsync(IdentityConfig.ApplicationUserManager manager)
{
return Task.FromResult(GenerateUserIdentity(manager));
}
public bool ReceiveNotifications { get; set; }
public int Permission { get; set; }
public virtual ICollection<Notificacao> Notificacoes { get; set; }
}
[Serializable]
public partial class Notificacao
{
public Notificacao()
{
this.Usuarios = new List<ApplicationUser>();
}
public int Codigo { get; set; }
public string Mensagem { get; set; }
public DateTime DataHoraNotificacao { get; set; }
public int Tipo { get; set; }
public virtual ICollection<ApplicationUser> Usuarios { get; set; }
}
Serialize方法,用于将对象序列化到Redis(在其中引发异常)
由于您无法控制包含IdentityUser类的资产,因此无法执行此操作。另一种解决方案可能是在缓存之前将对象映射到Dto(数据传输对象),而在获取时将对象映射到Dto(数据传输对象) 关于该主题的其他主题(与WCF相关,但仍涉及序列化IdentityUser):
您不想将IdentityUser或其任何子类序列化到数据库中。句号 若您需要维护数据库中的关系,请创建一个POCO(普通的旧CLR对象-简单地说,是一个自定义类)
此外,如果您需要在用户类中携带IdentityUser,请使用合成而不是继承。也就是说,不要继承自IdentityUser,而是在类中创建它的属性。并将该属性标记为不可序列化它没有标记为可序列化,您可以查看源代码:嗯,我明白了,好的,我会做decyclone建议,谢谢!
static byte[] Serialize(object o)
{
if (o == null)
{
return null;
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, o);
byte[] objectDataAsStream = memoryStream.ToArray();
return objectDataAsStream;
}
}