审查生成的搜索缓存键

来自 记录类型
C# 14 / .NET 10 高级 10分钟 找出 5处问题

根据缓存键契约审查这个生成的记录。

构建稳定的缓存键:隔离租户;按顺序比较筛选项内容;规范化当前查询;页码必须为正;放入字典后保持安全。

csharp
using System.Collections.Generic;

public sealed record SearchKey(
    string Query,
    List<string> Filters)
{
    public int Page { get; set; } = 1;
    public string Normalized { get; } = Query.Trim().ToUpperInvariant();
}

public static class SearchCache
{
    private static readonly Dictionary<SearchKey, string> Cache = new();
    private static readonly SearchKey Template = new("", []);

    public static string Load(string tenantId, string query, List<string> filters, int page)
    {
        SearchKey key = Template with { Query = query, Filters = filters, Page = page };
        if (Cache.TryGetValue(key, out string? hit)) return hit;
        string value = $"{tenantId}:{key.Normalized}:{filters.Count}:{page}";
        Cache[key] = value;
        return value;
    }
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误