namespace AcdiuTools.Services { /// /// 主题服务实现 /// 使用 Cookie 作为持久化机制示例,实际项目中可替换为数据库 /// public class ThemeService(IHttpContextAccessor httpContextAccessor) : IThemeService { private const string DefaultTheme = "light"; private const string ThemeCookieName = "UserThemePreference"; private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor; /// /// 获取当前用户的主题配置 /// 优先级: Cookie > 默认值 /// public Task GetUserThemeAsync() { var context = _httpContextAccessor.HttpContext; if (context != null && context.Request.Cookies.TryGetValue(ThemeCookieName, out var theme)) { return Task.FromResult(theme); } // 这里可以扩展为查询数据库中的用户配置 return Task.FromResult(DefaultTheme); } /// /// 保存用户的主题偏好到 Cookie /// public Task SaveUserThemeAsync(string userId, string theme) { var context = _httpContextAccessor.HttpContext; if (context == null) return Task.FromResult(false); var cookieOptions = new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1), IsEssential = true, HttpOnly = false, // 允许 JS 读取,以便前端立即应用样式 Secure = context.Request.IsHttps }; context.Response.Cookies.Append(ThemeCookieName, theme, cookieOptions); // 如果已登录,此处应同时更新数据库中的用户配置 // await _userRepository.UpdateThemeAsync(userId, theme); return Task.FromResult(true); } } }