【问题标题】:Static Id - ASP.NET Core Distributed Cache Tag Helper静态 ID - ASP.NET Core 分布式缓存标记帮助程序
【发布时间】:2021-07-19 18:42:41
【问题描述】:

我们将 ASP.NET Core 分布式缓存标记助手与 SQL 服务器一起使用。

<distributed-cache name="MyCacheItem1" expires-after="TimeSpan.FromDays(1)">
   <p>Something that will be cached</p>
   @DateTime.Now.ToString()
</distributed-cache>

它存储如下。

问题是 Id 列是自动散列的。我们希望在 Id 列中有一些有意义的字符串。 有可能吗?

【问题讨论】:

    标签: asp.net-core razor-pages distributed-caching


    【解决方案1】:

    问题是 Id 列是自动散列的。

    从源代码中,我们可以发现这似乎是一种设计行为:

    try
    {
        var serializedKey = Encoding.UTF8.GetBytes(key.GenerateKey());
        var storageKey = key.GenerateHashedKey();
        var value = await _storage.GetAsync(storageKey);
    
        //...
    
        //...
    
        await _storage.SetAsync(storageKey, encodeValue, options);
    

    我们希望在 Id 列中有一些有意义的字符串。有可能吗?

    如果您有特定的场景/需求需要Id 列的未哈希数据,您可以参考DistributedCacheTagHelperDistributedCacheTagHelperService 的源代码,然后实现自定义标签助手。

    【讨论】:

      【解决方案2】:

      谢谢@Fei Han。我从你的回答中得到了线索。

      将自定义字符串存储在 Id 列中。按照步骤操作。

      1. 使用 IDistributedCacheTagHelperService 实现自定义类(我创建的类似 HtmlDistributedCacheTagHelperService)

      2. 在启动时注入这个自定义类。 services.AddScoped();

      3. 复制 DistributedCacheTagHelperService (https://github.com/dotnet/aspnetcore/blob/52eff90fbcfca39b7eb58baad597df6a99a542b0/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperService.cs#L102) 的实际源代码。并粘贴到 HtmlDistributedCacheTagHelperService 中。

      4. 我添加了自定义属性 htmlcache-uniqueid。 htmlcache-uniqueid="CustomStringId">

      5. 在 HtmlDistributedCacheTagHelperService 类中,我在代码下方添加了我的自定义属性。

         if (output.Attributes != null && output.Attributes.Count > 0 &&
         string.Equals(output.Attributes[0].Name, "htmlcache-uniqueid") && 
         output.Attributes[0].Value != null)
        {
         storageKey = Convert.ToString(output.Attributes[0].Value);
        }
        
      6. 最后,您可以看到存储在 db 中的 id,如下所示。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-18
        • 2020-03-24
        • 1970-01-01
        • 1970-01-01
        • 2019-02-02
        • 2021-07-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多