Search code examples
asp.net-corerazor-pagesdistributed-caching

Static Id - ASP.NET Core Distributed Cache Tag Helper


We are using ASP.NET Core Distributed Cache Tag Helper with SQL server.

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

It stores as below. enter image description here

The problem is that Id column is automatically hashed. we want some meaningful string in Id column. Is it possible?


Solution

  • Thank you @Fei Han. I got clue from your answer.

    To store custom string in Id column. Follow the steps.

    1. Implement custom class using IDistributedCacheTagHelperService ( I created like HtmlDistributedCacheTagHelperService)

    2. Inject this custom class in startup. services.AddScoped<IDistributedCacheTagHelperService, HtmlDistributedCacheTagHelperService>();

    3. Copy actual source code of DistributedCacheTagHelperService (https://github.com/dotnet/aspnetcore/blob/52eff90fbcfca39b7eb58baad597df6a99a542b0/src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperService.cs#L102). and paste inside HtmlDistributedCacheTagHelperService.

    4. I added custom attribute htmlcache-uniqueid. <distributed-cache name="UniqueName" htmlcache-uniqueid="CustomStringId">

    5. Inside HtmlDistributedCacheTagHelperService class i added below code to get my custom attribute.

       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. finally you can see id stored in db like below. enter image description here