尝试实现IPrincipal (ASP.NET MVC3)时遇到问题:我的自定义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 例如,要获取UserId (示例:
( User as DealsPrincipal).UserId 这始终为空!为什么?我遗漏了什么?
发布于 2012-05-13 05:21:40
我需要更多的调查才能给你正确的答案,但看看这部分代码,它可以帮助你(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
https://stackoverflow.com/questions/10565547
复制相似问题