ASP.NET Core 2.1基于DB中的数据在布局中插入CSS

Sub*_*ive 3 css asp.net-core

我有一个问题,我正在努力.一些背景:用户可以在我的应用程序中选择要使用的应用程序的颜色方案,此选项存储在数据库中.

我想要做的是基于这个选择,在页面加载时,提供CSS文件以供用户选择.

我一直在尝试做的是通过在_Layout.cshtml页面中执行AJAX请求来检查用户选择,并将相应的CSS附加到标头.这是有效但不是很好,因为有一些延迟,它只是不是一个好的解决方案,因为有时在加载CSS后元素的样式不正确.

我想做的是检查服务器端,就像控制器中的普通视图一样(布局页面缺少控制器,因为你知道这就是我被困住的地方).然后在_Layout视图中添加正确的CSS.

亲爱的堆栈溢出,你对我有什么建议可以实现吗?我的用户需要甜蜜的黑暗主题.;)

提前致谢!

Chr*_*rdt 5

创建服务

public class ThemeService
{
    private readonly MyDbContext  _dbContext;
    private readonly IMemoryCache _memoryCache;

    public ThemeService(MyDbContext dbContext, IMemoryCache memoryCache)
    {
        //Here you can also inject the UserManager<T> if needed
        _dbContext = dbContext;
        _memoryCache = memoryCache;
    }

    public string GetTheme()
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其注册到服务容器scoped(因为您需要DbContext):

services.AddScoped<ThemeService, ThemeService>();
Run Code Online (Sandbox Code Playgroud)

在你看来,只需注入它

@inject ThemeService ThemeService;
Run Code Online (Sandbox Code Playgroud)

后来在视图中:

<link type="text/css" href="@ThemeService.GetTheme()" />
Run Code Online (Sandbox Code Playgroud)