Using ASP.NET Session State Provider with Azure Redis Cache

One of the possible configurations of the ASP.NET Session State Provider is using Azure Redis Cache.

The steps to follow are editing the web.config file,  creating the session helper class and customization of the ASP.NET Identity SignInManager.
The web.config configuration is very simple:

<system.web>
...
<sessionState mode="Custom" customProvider="RedisSessionProvider">
<providers>
<add name="RedisSessionProvider"
type="Microsoft.Web.Redis.RedisSessionStateProvider"
port="6380" host=""
accessKey=""
ssl="true" />
</providers>
</sessionState>
</system.web>

Then, the next step is implement the session helper class that contains the session properties:

public static class ApplicationSession
{
private static string _userName = "userName";
private static string _email = "email";
private static string _loginDate = "loginDate";

public static void Init(string userName, string email)
{
Set(_userName, userName);
Set(_email, email);
Set(_loginDate, DateTime.Now);
}

public static string UserName
{
get
{
return Get<string>(_userName);
}
set
{
Set(_userName, value);
}
}

public static string Email
{
get
{
return Get<string>(_email);
}
set
{
Set(_email, value);
}
}

public static DateTime StartDate
{
get
{
return Get<DateTime>(_loginDate);
}
set
{
Set(_loginDate, value);
}
}

private static T Get<T>(string key)
{
return (T) HttpContext.Current.Session[key];
}

private static void Set(string key, object value)
{
HttpContext.Current.Session[key] = value;
}
}

Finally, the initialization of the session datas through ASP.NET Identity SignInManager.
It’s necessary to override the PasswordSignInAsync method of the ApplicationSignInManager class:

public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
...

public override Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
Task<SignInStatus> status = base.PasswordSignInAsync(userName, password, isPersistent, shouldLockout);

if (status.Result == SignInStatus.Success)
{
ApplicationUser user = UserManager.FindByName(userName);
ApplicationSession.Init(user.UserName, user.Email);
}

return status;
}
}

The sample web project is available here.

Advertisements
Using ASP.NET Session State Provider with Azure Redis Cache

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s