2012-05-12 109 views
0

試圖實現的IPrincipal(ASP.NET MVC 3)有問題: 我自定義的IPrincipal:問題實施的IPrincipal

interface IDealsPrincipal: IPrincipal 
    { 
     int UserId { get; set; } 
     string Firstname { get; set; } 
     string Lastname { get; set; } 
    } 


public class DealsPrincipal : IDealsPrincipal 
    { 

     public IIdentity Identity { get; private set; } 
     public bool IsInRole(string role) { return false; } 

     public DealsPrincipal(string email) 
     { 
      this.Identity = new GenericIdentity(email); 
     } 

     public int UserId { get; set; } 
     public string Firstname { get; set; } 
     public string Lastname { get; set; } 

    } 

要序列化/解我用下面的類:

public class DealsPrincipalSerializeModel 
    { 
     public int UserId { get; set; } 
     public string Firstname { get; set; } 
     public string Lastname { get; set; } 
    } 

應用程序驗證事件如下(工作正常!)

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
     { 
      HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; 
      if (authCookie != null) 
      { 
       //get the forms ticket 
       FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); 
       //instantiate a new Deserializer 
       JavaScriptSerializer serializer = new JavaScriptSerializer(); 
       //deserialize the model 
       DealsPrincipalSerializeModel serializeModel = serializer.Deserialize<DealsPrincipalSerializeModel>(authTicket.UserData); 
       //put the values of the deserialized model into the HttpContext 
       DealsPrincipal newUser = new DealsPrincipal(authTicket.Name); //this implements IPrincipal 
       newUser.UserId = serializeModel.UserId; 
       newUser.Firstname = serializeModel.Firstname; 
       newUser.Lastname = serializeModel.Lastname; 

       HttpContext.Current.User = newUser;     
      } 
     } 

正如你在上一條語句中看到的那樣,HttpContext得到了這個新的DealsPrincipal(它工作正常)。

問題是,如果想在Controller(Action)中訪問這個用戶,我總是會得到一個基類對象。如果我投了用戶如下:

User as DealsPrincipal 

獲得例如用戶ID(示例:??

(User as DealsPrincipal).UserId 

這始終是零!爲什麼我缺少什麼

回答

0

我需要進行更多調查才能給出正確答案,但請查看代碼的這一部分,它可以幫助您(WindowsAuthenticationModule.cs的部分源代碼)

void OnAuthenticate(WindowsAuthenticationEventArgs e) { 
     //////////////////////////////////////////////////////////// 
     // If there are event handlers, invoke the handlers 
     if (_eventHandler != null) 
      _eventHandler(this, e); 

     if (e.Context.User == null) 
     { 
      if (e.User != null) 
       e.Context.User = e.User; 
      else if (e.Identity == _anonymousIdentity) 
       e.Context.SetPrincipalNoDemand(_anonymousPrincipal, false /*needToSetNativePrincipal*/); 
      else 
       e.Context.SetPrincipalNoDemand(new WindowsPrincipal(e.Identity), false /*needToSetNativePrincipal*/); 
     } 
    } 

從這段代碼我建議你在分配你的自定義IPrincipal實例之前檢查用戶是否是匿名的。另外,不確定此方法是在「protected void Application_AuthenticateRequest」之前還是之後執行的。將嘗試花更多時間來調查這一點。

另外,請看看這篇文章:

http://msdn.microsoft.com/en-us/library/ff649210.aspx