У меня есть собственная реализация 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 и заменяю
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, как предлагается здесь: inject-the-user-iprincipal">MVC3 + Ninject: Как правильно ввести IP-принцип пользователя? Я смогу получить доступ к @User.Identity.FirstName
в своем приложении.
Если это не так, какова цель привязки IPrincipal к HttpContext.Current.User, как показано в связанном вопросе?