我正在使用ASP.NET核心和标识3。
当我登录时,我读取当前select用户界面模板,并在我的_Layout.cshml
文件中基于该模板加载css
。
用户可以更改他的主题,我通过控制器将其存储在会话变量中。
public IActionResult ChangeTheme(int id, string returnUrl)
{
HttpContext.Session.SetInt32("Template", (id));
return Redirect(returnUrl);
}
与每次加载cshtml
查询数据库不同,我将模板放在会话变量中,在Layout.cshtml
中根据模板呈现不同的css。
switch (template)
{
case (int)TemplateEnum.Template2:
<text>
<link rel="stylesheet" href="~/css/template1.css" />
</text>
break;
case (int)TemplateEnum.Template2:
<text>
<link rel="stylesheet" href="~/css/template2.css" />
</text>
break;
{
我想知道如果会议结束了会发生什么。
_Layout.cshtml
中的值,如果它变为null,并且在呈现新页面之前立即从db加载它,那么它就在那里了。发布于 2016-02-22 13:35:19
我没有每次加载cshtml来查询数据库,而是将模板放在会话变量中,并在Layout.cshtml中根据模板呈现不同的css。
如果访问数据库是您唯一关心的问题,并且您已经抽象了您的存储库(或者用户存储库,如果您将它存储在标识类型上),那么您可以使用装饰器模式来实现本地缓存。
public interface IUserRepository
{
string GetUserTheme(int userId);
void SetUserTheme(int userId, string theme);
}
public class CachedUserRepository : IUserRepository
{
private readonly IMemoryCache cache;
private readonly IUserRepository userRepository;
// Cache Expire duration
private static TimeSpan CacheDuration = TimeSpan.FromMinutes(5);
public CachedUserRepository(IUserRepository userRepository, IMemoryCache memoryCache)
{
if (userRepository == null)
throw new ArgumentNullException(nameof(userRepository));
if (memoryCache == null)
throw new ArgumentNullException(nameof(memoryCache));
this.userRepository = userRepository;
this.cache = memoryCache;
}
public string GetUserTheme(int userId)
{
string theme;
// adding a prefix to make the key unique
if (cache.TryGetValue($"usertheme-{userId}", out theme))
{
// found in cache
return theme;
};
// fetch from database
theme = userRepository.GetUserTheme(userId);
// put it into the cache, expires in 5 minutes
cache.Set($"usertheme-{userId}", theme, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = CacheDuration });
return theme;
}
public void SetUserTheme(int userId, string theme)
{
// persist it
userRepository.SetUserTheme(userId, theme);
// put it into the cache, expires in 5 minutes
cache.Set($"usertheme-{userId}", theme, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = CacheDuration });
}
}
问题是,在默认的ASP.NET核心DI系统中,不存在对装饰器的内置支持。您必须使用第三方IoC容器(Autofac、StructureMap等)。
你当然可以这样注册
services.AddScoped<IUserRepository>(container => {
return new CachedUserRepository(container.GetService<UserRepository>(), container.GetServices<IMemoryCache>());
});
但这有点麻烦。否则,将其存储在一个长期存在的cookie中,它的优点是,当用户未登录时,主题仍然处于活动状态,并且您可以在用户登录时设置cookie。
发布于 2016-02-22 12:06:26
如果您愿意,当然可以将主题存储在用户的标识中,但是无论何时更新主题,您都必须辞职。
你会做这样的事情:
userManager.AddClaimAsync(user, new Claim("Template", id+""));
signInManager.SignInAsync(user);
https://stackoverflow.com/questions/35561070
复制