如何解决静态 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>
问题是 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
列的未散列数据,您可以参考 DistributedCacheTagHelper
和 DistributedCacheTagHelperService
的源代码,然后实现自定义标签助手。
谢谢@费涵。我从你的回答中得到了线索。
在 Id 列中存储自定义字符串。按照步骤操作。
-
使用 IDistributedCacheTagHelperService 实现自定义类(我像 HtmlDistributedCacheTagHelperService 一样创建)
-
在启动时注入这个自定义类。 services.AddScoped
(); -
复制 DistributedCacheTagHelperService (https://github.com/dotnet/aspnetcore/blob/52eff90fbcfca39b7eb58baad597df6a99a542b0/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperService.cs#L102) 的实际源代码。并粘贴到 HtmlDistributedCacheTagHelperService 中。
-
我添加了自定义属性 htmlcache-uniqueid。
htmlcache-uniqueid="CustomStringId"> -
在 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); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。