wog*_*les 1 asp.net-mvc twitter-bootstrap owin asp.net-identity
我想在我的MVC 5应用程序中包含对bootswatch主题的主题支持.
我希望用户主题在登录时保存并加载.
我扩展了我的用户类以包含主题,并且可以在编辑用户页面上成功设置和保存主题.
public class User : IdentityUser
{       
public string BootstrapTheme {get;set;}
}
在BootstrapTheme属性中,我将保存bootstrap css链接的href属性.例如  "~/Content/bootstrap.flatly.min.css"
计划是在布局页面中设置主题.
<link href="~/Content/bootstrap.spacelab.min.css" rel="stylesheet" />
如何在不加载每个页面的情况下查询数据库的情况下如何执行此操作?
能够做一些像<link href="@User.BootstrapTheme" rel="stylesheet" />理想的事情.
以下是使用localstorage http://wdtz.org/bootswatch-theme-selector.html保存一页的链接
您应该将主题名称/ url存储为用户的声明,而不是作为User该类的一部分:
await userManager.AddClaimAsync(user.Id, new Claim("MyApp:ThemeUrl", "~/Content/bootstrap.flatly.min.css"));
当用户登录时,此声明将添加到cookie中,您可以通过扩展方法访问它:
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";
}
并在您的视图中,您将访问这样的主题网址:
<link href="@ClaimsPrincipal.Current.GetThemeUrl()" rel="stylesheet" />
Cookie中提供了对主体的声明,因此不需要额外的数据库命中.
作为替代方案,您可以BootstrapTheme像已经完成的那样持久保存用户,但是当用户登录时,将此主题添加为对标识的声明:
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);
}
然后通过上述扩展方法访问视图中的声明.我最近在博客中谈到了类似的情况 - 您可以在那里了解一下索赔的工作方式.
| 归档时间: | 
 | 
| 查看次数: | 2609 次 | 
| 最近记录: |