Det sparas inte mellan anropen, du måste skapa ditt objekt vid varje anrop. Titta på global.asax, det finns en metod där som du kan överlagra, och då där köra din kod.
Jag använder idag FormsAuthentication i en MVC site och skulle vilja utöka användarobjektet på ett bra sätt så att jag kan skicka med inställningar såsom namn, användarbild och liknande. Men hur gör jag det? Jag har läst om att ärva från IPrincipal eller GenericPrincipal men får inte riktigt till det.
Kan det vara så att min CustomPrincipal inte sparas mellan anropen? Jag får följande felmeddelande:
Unable to cast object of type 'System.Security.Principal.GenericPrincipal' to type 'MVC3Test.Infrastructure.CustomPrincipal'.
Jag försöker hämta värdet i min vy (aspx/cshtml sidan)
((MVC3Test.Infrastructure.CustomPrincipal)Context.User).Identity.Name
I inloggningen gör jag följande när användarens användarnamn och lösenord stämmer.
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName];
if (null == authCookie)
{
// There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
// Log exception details (omitted for simplicity)
return;
}
// Create a new principal
FormsIdentity id = new FormsIdentity(authTicket);
string[] roles = authTicket.UserData.Split('|');
CustomPrincipal principal = new CustomPrincipal(id, roles);
principal.FirstName = "Sven";
// Attach the new principal object to the current HttpContext object
HttpContext.Current.User = principal;
Här försöker jag utöka IPrincipal
public class CustomPrincipal : IPrincipal
{
private IIdentity _identity;
private string[] _roles;
public string FirstName { get; set; }
public CustomPrincipal(IIdentity identity, string[] roles)
{
_identity = identity;
_roles = new string[roles.Length];
roles.CopyTo(_roles, 0);
Array.Sort(_roles);
}
#region IPrincipal Members
public IIdentity Identity
{
get
{
return _identity;
}
}
public bool IsInRole(string role)
{
return Array.BinarySearch(_roles, role) >= 0 ? true : false;
}
#endregion
}
