November 14, 2016 by Anuraj
ASP.NET Core Redis Cache Session
This post is about Configuring Redis for ASP.NET Core Session Store. Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries. Redis works with an in-memory dataset. it also supports persisting the dataset to disk. Moreover, It provides master-slave asynchronous replication. Redis is not officially supported on windows. However, the Microsoft Open Tech group develops and maintains Windows port targeting Win64 available here. You can install redis using chocolatey package manager, using
choco install redis-64 command. Once you install redis you can run
redis-server command to start the redis server.
You can test the installation using
redis-cli command. You can set and get the values. For setting the values you need to use command like
set key value and for getting the values
get key. To list all the keys you can execute
keys * command. To remove all the values
flushall command can be used.
To use Redis in ASP.NET Core, you need to reference,
Microsoft.Extensions.Caching.Redis.Core package. And you can configure the Redis Cache using
AddDistributedRedisCache method in the
Unlike previous versions of ASP.NET, Session in ASP.NET Core doesn’t will not be available by default. You need to configure session. To use session first you need to update the project.json with
Microsoft.AspNetCore.Session package. And once you added it you need to add session and configure it.
And here is the project.json file changes
Now in code you can use Set and TryGetValue methods to set and get values from session.
And here is the code to get values.
Get and Set methods in session is accepting byte array, so you need to convert string values to bytes.
Happy Programming :)
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub