2012-05-12 80 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