添加项目文件。
This commit is contained in:
26
Services/IThemeService.cs
Normal file
26
Services/IThemeService.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AcdiuTools.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// 主题服务接口
|
||||
/// 负责处理用户主题偏好的获取与持久化
|
||||
/// </summary>
|
||||
public interface IThemeService
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取当前用户的主题配置
|
||||
/// 如果用户未登录或未设置,返回默认主题
|
||||
/// </summary>
|
||||
/// <returns>主题名称 (如 "light", "dark")</returns>
|
||||
Task<string> GetUserThemeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// 保存用户的主题偏好
|
||||
/// </summary>
|
||||
/// <param name="userId">用户ID</param>
|
||||
/// <param name="theme">主题名称</param>
|
||||
/// <returns>是否保存成功</returns>
|
||||
Task<bool> SaveUserThemeAsync(string userId, string theme);
|
||||
}
|
||||
}
|
||||
53
Services/ThemeService.cs
Normal file
53
Services/ThemeService.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
namespace AcdiuTools.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// 主题服务实现
|
||||
/// 使用 Cookie 作为持久化机制示例,实际项目中可替换为数据库
|
||||
/// </summary>
|
||||
public class ThemeService(IHttpContextAccessor httpContextAccessor) : IThemeService
|
||||
{
|
||||
private const string DefaultTheme = "light";
|
||||
private const string ThemeCookieName = "UserThemePreference";
|
||||
private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor;
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前用户的主题配置
|
||||
/// 优先级: Cookie > 默认值
|
||||
/// </summary>
|
||||
public Task<string> GetUserThemeAsync()
|
||||
{
|
||||
var context = _httpContextAccessor.HttpContext;
|
||||
if (context != null && context.Request.Cookies.TryGetValue(ThemeCookieName, out var theme))
|
||||
{
|
||||
return Task.FromResult(theme);
|
||||
}
|
||||
|
||||
// 这里可以扩展为查询数据库中的用户配置
|
||||
return Task.FromResult(DefaultTheme);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存用户的主题偏好到 Cookie
|
||||
/// </summary>
|
||||
public Task<bool> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user