entity-framework - ASP.NET Core MVC 自定义站点变量
问题描述
我有一个 ASP.NET Core MVC(带有 EF)站点,我希望管理员通过管理面板修改一些变量。例如联系电子邮件、柜台部分可见性、导航菜单可见性等。
而且大部分参数都在_Layout.cshtml
.
我可以学习如何管理此问题的最佳实践。
例如:我有一个名为 GeneralSettings 的单行表,它有一些列(IsLoginEnable、IsPrivacyVisible 等)并且想在 _Layout.cshtml 中读取这些列
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
@if (true) //for example I want to write here "if (Model.ToList()[0].IsLoginEnable)" instead of this
{
<partial name="_LoginPartial" />
}
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
@if (true) //if (Model.ToList()[0].IsPrivacyVisible)
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
}
</ul>
我在我真正想做的 if 条件附近添加了评论。
解决方案
更新的答案
GeneralSettings
在应用程序第一次启动时播种。- 管理员可以使用常规表单从 UI 修改它。
- 需要时,通过
IMemoryCache
服务从服务器的内存中获取。如果它不存在于内存中,则从数据库中获取它并缓存它。 - 当发生修改时
GeneralSettings
,使用服务将其从内存中清除IMemoryCache
。
下面的代码只是一个示例,可能需要修改才能在您的应用程序中工作。
把你GeneralSettings
变成服务:
public Interface IGeneralSettingsService
{
Task<GeneralSettings> GetSettingsAsync();
}
public class GeneralSettingsRepo : IGeneralSettingsService
{
//Inject Context...
//Inject IMemoryCache...
public async Task<GeneralSettings> GetSettingsAsync()
{
if (!memoryCache.TryGetValue("GeneralSettings", out GeneralSettings GS))
{
GS = await context.GeneralSettings.AsNoTracking().FirstOrDefaultAsync();
_ = memoryCache.Set<GeneralSettings>("GeneralSettings", GS, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(cachehours),
SlidingExpiration = TimeSpan.FromHours(cachehours)
});
}
return GS;
}
}
在您的管理控制器中:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UpdateGlobalSettings(SettingsVm vm)
{
//Update properties...
memoryCache.Remove("GeneralSettings"); //Purge old settings from cache
}
最后在你Layout.cshtml
注入设置服务:
@inject IGeneralSettingsService GeneralSettingsService
@{
var settings = await GeneralSettingsService.GetSettingsAsync();
}
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
@if (settings.IsLoginEnabled)
{
<partial name="_LoginPartial" />
}
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
@if (settings.IsPrivacyVisible)
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
}
</ul>
不要忘记在ConfigureServices
.