静态 ID - ASP.NET Core 分布式缓存标签助手

问题描述

我们正在将 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>

它存储如下。

enter image description here

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

解决方法

问题是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 的源代码,然后实现自定义标签助手。

,

谢谢@费涵。我从你的回答中得到了线索。

在 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. 最后你可以看到 id 存储在 db 中,如下所示。 enter image description here