Asp.net-Mvc-2

在 MVC 中實現自定義身份和 IPrincipal

  • December 10, 2009

我有一個基本的 MVC 2 beta 應用程序,我試圖在其中實現自定義 Identity 和 Principal 類。

我創建了實現 IIdentity 和 IPrincipal 介面的類,將它們實例化,然後在 Global.asax 的 Application_AuthenticateRequest 中將 CustomPrincipal 對象分配給我的 Context.User。

這一切都成功了,對像看起來不錯。當我開始呈現視圖時,頁面現在失敗了。第一個失敗是在以下程式碼行的預設 LogoOnUserControl 視圖中:

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

如果我把它拉出來,那麼它會在不同的“Html.ActionLink”程式碼行上失敗。

我收到的錯誤是:

WebDev.WebHost40.dll 中出現“System.Runtime.Serialization.SerializationException”類型的異常,但未在使用者程式碼中處理

附加資訊:未解析成員“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 介面或繼承 GenericIdentity/GenericPrincipal,它會失敗並出現上述原始錯誤。

我在網路的幫助下想出了這個:) 訣竅是您必須在實現 IIdentity 的類中實現 ISerializable 介面。我希望這有助於節省其他人一些時間:)

類聲明:

[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

這是文章的連結,其中包含有關“功能”的更多詳細資訊

引用自:https://stackoverflow.com/questions/1884030