DNN Forums

Ask questions about your website to get help learning DNN and help resolve issues.

How to Apply Cache in API

 4 Replies
 2 Subscribed to this topic
 14 Subscribed to this forum
Sort:
Author
Messages
New Around Here
Posts: 1
New Around Here

    Hii team,

    I am using DNN API to fetch frequently data by using Ajax. So I did't find answer How to cache API in DNN. Please suggest

       public class StockTickerController : DnnApiController
        {

              [HttpGet]
            public HttpResponseMessage DSIJIncludeTickerGraph()
            {

    return Request.CreateResponse(HttpStatusCode.OK, new { CurrentBseNseValue = AllCurrentBseNseValueVr }); 

             }

        }

     

    New Around Here
    Posts: 6
    New Around Here

      I know this is almost a year old however, you can use a CacheHelper class like you would for module data:

      using DotNetNuke.Common.Utilities;
      ...

      public class CacheHelper
      {
          public static bool CacheExists(string key)
          {
              return DataCache.GetCache(key) != null;
          }

          public static void SetCache(T toSet, string key)
          {
              DataCache.SetCache(key, toSet);
          }

          public static T GetItemFromCache(string key)
          {
              return (T)DataCache.GetCache(key);
          }
      }

      Then in the API, you would call the static functions to check if there is cache, or if you need to collect the data from the source. You'll need to supply some sort of key. Here is an example for collecting Events from calendars in Office 365

      [AllowAnonymous]
      [HttpGet]
      public async Task GetCalendarViews(string UserPrimaries, string start, string end)
      {
          var Events = new List();
          if (CacheHelper.CacheExists(UserPrimaries))
          {
              Events.AddRange(CacheHelper.GetItemFromCache< List>(UserPrimaries));
          }
          else
          {
              // make data calls and get Graph Events
              ...
              CacheHelper.SetCache(Events, UserPrimaries);
          }

          return new HttpResponseMessage()
          {
              StatusCode = HttpStatusCode.OK,
              Content = new StringContent(Events.ToJson(), System.Text.Encoding.UTF8, "application/json")
          };
      }

      Happy DNNing

      Senior Member
      Posts: 1425
      Senior Member
        Posted By Ryan Jagdfeld on 9/6/2023 5:51 AM

        I know this is almost a year old however, you can use a CacheHelper class like you would for module data:

        using DotNetNuke.Common.Utilities;
        ...

        public class CacheHelper
        {
            public static bool CacheExists(string key)
            {
                return DataCache.GetCache(key) != null;
            }

            public static void SetCache(T toSet, string key)
            {
                DataCache.SetCache(key, toSet);
            }

            public static T GetItemFromCache(string key)
            {
                return (T)DataCache.GetCache(key);
            }
        }

        Then in the API, you would call the static functions to check if there is cache, or if you need to collect the data from the source. You'll need to supply some sort of key. Here is an example for collecting Events from calendars in Office 365

        [AllowAnonymous]
        [HttpGet]
        public async Task GetCalendarViews(string UserPrimaries, string start, string end)
        {
            var Events = new List();
            if (CacheHelper.CacheExists(UserPrimaries))
            {
                Events.AddRange(CacheHelper.GetItemFromCache< List>(UserPrimaries));
            }
            else
            {
                // make data calls and get Graph Events
                ...
                CacheHelper.SetCache(Events, UserPrimaries);
            }

            return new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content = new StringContent(Events.ToJson(), System.Text.Encoding.UTF8, "application/json")
            };
        }

        Happy DNNing

        Nice catch on finding and responding to this old question... This is always helpful to our community.  Thank you!  💪🏽 

         

        New Around Here
        Posts: 1
        New Around Here

          Ryan's solution works well but does not protect against a scenario where DNN's cache is cleared and the API endpoint is down. Clearing the cached API data in this scenario would break the application. Is there a way to call the API endpoint before clearing the cached API data and only proceed with clearing that cache if the API call was successful and can be immediately re-cached? I looked into the DNNCacheDependency parameter for the SetCache method, but I'm not sure it accomodates this scenario.

          Advanced Member
          Posts: 232
          Advanced Member
            I have done something similar in the past. It is a pattern that goes by multiple names "cache stack" or "cache castle" or "Tiered Caching", "Multi-level caching". I remember building this all by hand and then finding a Nuget package that did just that (can't remember the name now)...

            Basically, you have multiple caches.
            Cache A Is fast, in-memory and is guaranteed to expire in say 20 minutes or whatever you consider is fresh enough.
            Cache B could be in memory, disc, or database and is refreshed periodically but does not auto-expire, a scheduled task will refresh it every10 minutes let's say. If that API call fails, it stays as is.
            Finaly Cache A feeds of off cache B instead of the actual source that could be down or brittle.

            That way in most scenarios you get proper cache and source, but if the source of truth goes down, you get the last info obtained.

            These Forums are dedicated to the discussion of DNN Platform.

            For the benefit of the community and to protect the integrity of the ecosystem, please observe the following posting guidelines:

            1. If you have (suspected) security issues, please DO NOT post them in the forums but instead follow the official DNN security policy
            2. No Advertising. This includes the promotion of commercial and non-commercial products or services which are not directly related to DNN.
            3. No vendor trolling / poaching. If someone posts about a vendor issue, allow the vendor or other customers to respond. Any post that looks like trolling / poaching will be removed.
            4. Discussion or promotion of DNN Platform product releases under a different brand name are strictly prohibited.
            5. No Flaming or Trolling.
            6. No Profanity, Racism, or Prejudice.
            7. Site Moderators have the final word on approving / removing a thread or post or comment.
            8. English language posting only, please.

            Would you like to help us?

            Awesome! Simply post in the forums using the link below and we'll get you started.

            Get Involved