gpt4 book ai didi

asp.net-mvc-2 - 在 MVC 中实现自定义身份和 IPrincipal

转载 作者:行者123 更新时间:2023-12-03 12:38:36 25 4
gpt4 key购买 nike

我有一个基本的 MVC 2 beta 应用程序,我试图在其中实现自定义 Identity 和 Principal 类。

我创建了实现 IIdentity 和 IPrincipal 接口(interface)的类,将它们实例化,然后在 Global.asax 的 Application_AuthenticateRequest 中将 CustomPrincipal 对象分配给我的 Context.User。

这一切都成功了,对象看起来不错。当我开始呈现 View 时,页面现在失败了。第一个失败是在以下代码行的默认 LogoOnUserControl View 中:

 [ <%= Html.ActionLink("Log Off", "LogOff", "Account") %> ]

如果我把它拉出来,那么它会在不同的“Html.ActionLink”代码行上失败。

我收到的错误是:

An exception of type 'System.Runtime.Serialization.SerializationException' occurred in WebDev.WebHost40.dll but was not handled in user code

Additional information: Type is not resolved for member 'Model.Entities.UserIdentity,Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.



为了在 MVC 中使用自定义身份,我需要在身份中实现一些其他属性吗?我试图在 Identity 类中实现 [Serializable()] 但它似乎没有影响。

更新:
我已经尝试了 3-4 种替代方法来实现这一点,但仍然失败并出现同样的错误。如果我直接使用 GenericIdentity/GenericPrincipal 类,它不会出错。
GenericIdentity ident = new GenericIdentity("jzxcvcx");
GenericPrincipal princ = new GenericPrincipal(ident, null);
Context.User = princ;

但这让我无处可去,因为我试图使用 CustomIdentity 来保存几个属性。如果我为我的 CustomIdentity/CustomPrincipal 实现 IIdentity/IPrincipal 接口(interface)或继承 GenericIdentity/GenericPrincipal ,则会出现上述原始错误。

最佳答案

我在网络的帮助下想出了这个:) 诀窍是您必须在实现 IIdentity 的类中实现 ISerializable 接口(interface)。我希望这有助于节省其他人一些时间:)

类声明:

[Serializable]
public class ForumUserIdentity : IIdentity, ISerializable

ISerializable 的实现:
#region ISerializable Members

public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (context.State == StreamingContextStates.CrossAppDomain)
{
GenericIdentity gIdent = new GenericIdentity(this.Name, this.AuthenticationType);
info.SetType(gIdent.GetType());

System.Reflection.MemberInfo[] serializableMembers;
object[] serializableValues;

serializableMembers = FormatterServices.GetSerializableMembers(gIdent.GetType());
serializableValues = FormatterServices.GetObjectData(gIdent, serializableMembers);

for (int i = 0; i < serializableMembers.Length; i++)
{
info.AddValue(serializableMembers[i].Name, serializableValues[i]);
}
}
else
{
throw new InvalidOperationException("Serialization not supported");
}
}

#endregion

这里是 link to the article that has more detail on the "Feature"

关于asp.net-mvc-2 - 在 MVC 中实现自定义身份和 IPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1884030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com