0

I stored values in my cache using my Controller class using the dependency IMemoryCache. I am also accessing my cache and get few values from it like so:

//IMemoryCache initailized before this variable : _cache
public void foo()
{
   var token = _cache.Get<TokenModel>("Token" + HttpContext.Session.GetString("TokenGuid"));
   //Do something with token
}

Question is:
How can I can access the cache from my Javascript file?

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
Hexxed
  • 683
  • 1
  • 10
  • 28
  • Could you please explain what do you mean by accessing cache from javascript file? Javascript is being executed on client side (browser) there is no way to access directly cache on the server. – Szymon Tomczyk Nov 08 '18 at 11:57
  • If I understand correctly what you want to do is basically send a json object from your server to the client and grab it with js? Don't know if you can do this with IMemoryCache though. – Jabberwocky Nov 08 '18 at 11:59
  • ohh then I would be needing another approach then thanks – Hexxed Nov 08 '18 at 11:59

2 Answers2

0

Cache is located on the server while JavaScript is executed on the client. The only way I can think of is if you create a cache controller and create a Get action on it. After that you would call this action in Ajax and asynchronously get the server cache value.

public class CacheController : Controller
{
   [HttpGet("{key}")]
   public IActionResult GetCacheValue(string key)
   {
       var cacheValue = //get your cache
       return Json(cacheValue);
   }
}
Robert
  • 2,407
  • 1
  • 24
  • 35
0

IMemoryCache allows you to speed up your application by storing your data "in-memory". So you can reach memory from your javascript code.

Please have a look to the documentation of the IMemoryCache here: https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-2.1

What I would suggest you is get your cached data on backend side and put it cookie. Then later you can get cookie value from your javascript code.

I assume you have an instance of IMemoryCache which name is _cache.

You can set cache by like this.

 _cache.Set(cacheKey, cacheEntry, cacheEntryOptions);

HttpCookie myCookie = new HttpCookie("yourCookieName");
myCookie["cacheData"] = cacheEntry;
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);

or you can do the same after you get your cached data. Just get the data from your memory and set it to cookie.

You can get the cookie from your Javascript by using both DOM or JQuery.

If you would like to use DOM:

var x = document.cookie;

For jquery have a look at this answer on StackOverFlow: https://stackoverflow.com/a/1599367/1261525

Mehmet Taha Meral
  • 3,315
  • 28
  • 30