コード例 #1
0
        public async Task <ActionResult <SWCharacter> > GetById(int id)
        {
            // invalid parameter passed case
            if (id < 1)
            {
                return(NotFound());
            }
            SWCharacter myCharacter;

            //access cache
            if (!_cache.TryGetValue(id, out SWCharacter characterCacheEntry))
            {
                //entity not stored in cache , retrieve and cache it.
                //...
                SWCharRootObject myChar = await _swapiService.PopulateCharacterData(id);

                // retrieve character's planet data , extract id from character root object  homeplanet slot.

                string planetId = Regex.Match(myChar.homeworld, @"\d+").Value;

                SWPlanetRootObject itsPlanet = await _swapiService.PopulatePlanetData(int.Parse(planetId));

                //Generate a Character viewModel using populated data from swapi...

                myCharacter = _swapiService.GenerateNewCharacter(id, myChar, itsPlanet);

                //replace path to species with  species name

                string speciesId = Regex.Match(myCharacter.Species_Name, @"\d+").Value;

                myCharacter.Species_Name = await _swapiService.GetSpeciesName(int.Parse(speciesId));

                myCharacter.Average_Rating = 1;
                myCharacter.Max_Rating     = 1;

                //generate options required by memcache module...
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                                        // Set cache entry size by extension method.
                                        .SetSize(1)
                                        // Keep in cache for this time, reset time if accessed.
                                        .SetSlidingExpiration(TimeSpan.FromSeconds(3600));

                // finaly , store it in memcache...
                _cache.Set(id, myCharacter, cacheEntryOptions);
            }
            else
            {
                // cache entry found...
                myCharacter = characterCacheEntry;
            }



            if (myCharacter == null)
            {
                return(NotFound());
            }
            else
            {
                return(myCharacter);
            }
        }