Click here to Skip to main content
15,921,250 members
Articles / Hosted Services / Azure

Azure Cache in ASP.NET Core 2.0

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
1 Sep 2017CPOL 4.3K   1  
How to use Azure Redis cache in ASP.NET Core. Continue reading...

Problem

How to use Azure Redis cache in ASP.NET Core.

Solution

Create a class library and add NuGet packages:

  • StackExchange.Redis
  • Newtonsoft.Json

Add a class to encapsulate settings:

C#
public AzureCacheSettings(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("ConnectionString");

            this.ConnectionString = connectionString;
        }

        public string ConnectionString { get; }
    }

Add a class for cache storage. Add a constructor and private methods to initialize the Azure client:

C#
public AzureCacheStorage(AzureCacheSettings settings)
        {
            this.settings = settings;
            Init();
        }
        private AzureCacheSettings settings;
        private ConnectionMultiplexer connection;
        private IDatabase database;
        private IServer server;

        private void Init()
        {
            connection = ConnectionMultiplexer.Connect(settings.ConnectionString);
            database = connection.GetDatabase();
            server = connection.GetServer(connection.GetEndPoints().First());
        }

Now methods to access the cache:

C#
public async Task SetStringAsync(string key, string value)
        {
            await database.StringSetAsync(key, value);
        }

        public async Task SetObjectAsync(string key, object value)
        {
            await database.StringSetAsync(key, JsonConvert.SerializeObject(value));
        }

        public async Task<string> GetStringAsync(string key)
        {
            var value = await database.StringGetAsync(key);
            return value.IsNullOrEmpty ? "" : value.ToString();
        }

        public async Task<T> GetObjectAsync<T>(string key)
        {
            var value = await database.StringGetAsync(key);
            return value.IsNullOrEmpty ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }

        public async Task<bool> ExistAsync(string key)
        {
            return await database.KeyExistsAsync(key);
        }

        public async Task DeleteAsync(string key)
        {
            await database.KeyDeleteAsync(key);
        }

Inject and use the class:

C#
[Route("movies")]
    public class MoviesController : Controller
    {
        private readonly IAzureCacheStorage cacheStorage;

        public MoviesController(IAzureCacheStorage cacheStorage)
        {
            this.cacheStorage = cacheStorage;
        }

        [HttpGet]
        public async Task<IActionResult> Get()
        {
            var keys = this.cacheStorage.ListKeys();

            return Ok(keys);
        }

        [HttpGet("{id}", Name = "GetMovie")]
        public async Task<IActionResult> Get(string id)
        {
            var model = await this.cacheStorage.GetObjectAsync<Movie>(id);

            return Ok(model);
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody]Movie model)
        {
            await this.cacheStorage.SetObjectAsync(model.Id.ToString(), model);

            return CreatedAtRoute("GetMovie", new { id = model.Id }, model);
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(string id)
        {
            await this.cacheStorage.DeleteAsync(id);

            return NoContent();
        }
    }

In ASP.NET Core Web Application, configure services:

C#
public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddScoped<IAzureCacheStorage>(factory =>
            {
                return new AzureCacheStorage(new AzureCacheSettings(
                    connectionString: Configuration["Cache_ConnectionString"]));
            });

            services.AddMvc();
        }

Discussion

The sample code will require you to setup Azure account and Redis cache. Instructions for these could be found here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --