You should store theme name/url as a claim on the user, not as part of the User
class:
await userManager.AddClaimAsync(user.Id, new Claim("MyApp:ThemeUrl", "~/Content/bootstrap.flatly.min.css"));
When user is logged in, this claim is added to the cookie and you can access it through extension method:
public static String GetThemeUrl(this ClaimsPrincipal principal)
{
var themeClaim = principal.Claims.FirstOrDefault(c => c.Type == "MyApp:ThemeUrl");
if (themeClaim != null)
{
return themeClaim.Value;
}
// return default theme url if no claim is set
return "path/to/default/theme";
}
and in your view you would access theme url like this:
<link href="@ClaimsPrincipal.Current.GetThemeUrl()" rel="stylesheet" />
Claims on principal are available in the cookie, so no extra DB hits required.
As an alternative you can persist user BootstrapTheme
as you already have done, but when user is logging in, add this theme as a claim to the identity:
public async Task SignInAsync(IAuthenticationManager authenticationManager, ApplicationUser applicationUser, bool isPersistent)
{
authenticationManager.SignOut(
DefaultAuthenticationTypes.ExternalCookie,
DefaultAuthenticationTypes.ApplicationCookie);
var identity = await this.CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim("MyApp:ThemeUrl", applicationUser.BootstrapTheme));
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
And then access the claim in the view via above-mentioned extension method. I've blogged recently about similar scenario - you can have a look there for a bit more insight how claims work.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…