我有一个自定义的 IIdentity 实现:
public class FeedbkIdentity : IIdentity
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Name { get; set; }
public FeedbkIdentity()
{
// Empty contructor for deserialization
}
public FeedbkIdentity(string name)
{
this.Name = name;
}
public string AuthenticationType
{
get { return "Custom"; }
}
public bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(this.Name); }
}
}
和自定义 IPrincipal
public class FeedbkPrincipal : IPrincipal
{
public IIdentity Identity { get; private set; }
public FeedbkPrincipal(FeedbkIdentity customIdentity)
{
this.Identity = customIdentity;
}
public bool IsInRole(string role)
{
return true;
}
}
在 global.asax.cs 我反序列化 FormsAuthenticationTicket userData 并替换
HttpContext.Current.User:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
JavaScriptSerializer serializer = new JavaScriptSerializer();
FeedbkIdentity identity = serializer.Deserialize<FeedbkIdentity>(authTicket.UserData);
FeedbkPrincipal newUser = new FeedbkPrincipal(identity);
HttpContext.Current.User = newUser;
}
}
然后,在 Razor Views 中,我可以这样做:
@(((User as FeedbkPrincipal).Identity as FeedbkIdentity).FirstName)
我已经在使用 Ninject 为会员提供者注入自定义用户存储库,并且我一直在尝试将 IPrincipal 绑定到 HttpContext.Current.User:
internal class NinjectBindings : NinjectModule
{
public override void Load()
{
Bind<IUserRepository>().To<EFUserRepository>();
Bind<IPrincipal>().ToMethod(ctx => ctx.Kernel.Get<RequestContext>().HttpContext.User).InRequestScope();
}
}
但它不起作用。
我要做的就是能够像这样访问我的自定义 IIdentity 属性:
@User.Identity.FirstName
我怎样才能使这项工作?
编辑
我期待通过将 IPrincipal 绑定到 HttpContext.Current.User 如下所示:MVC3 + Ninject:注入用户 IPrincipal 的正确方法是什么?我将能够@User.Identity.FirstName
在我的应用程序中访问。
如果不是这种情况,如链接问题所示,将 IPrincipal 绑定到 HttpContext.Current.User 的目的是什么?