4

I have an Azure PaaS that I want to configure for high availability and I have added another role to the instance and now I need to configure ASP.Net session to be stored within a distributed cache. I have found the following information in regards to how to use the cache:

http://azure.microsoft.com/en-us/documentation/articles/cache-dotnet-how-to-use-azure-redis-cache/#store-session

I have logged into Azure and created a preview Cache. I added the StackExchange.Redis nuget package and the RedisSessionStateProvider nuget and my web config now looks as follows:

<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
    <section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />    
  </configSections>

  <connectionStrings>
    <add name="MetaLearningContext" connectionString="Data Source=server.database.windows.net;Initial Catalog=databasename;User ID=admin@server;Password=password;" providerName="System.Data.SqlClient" />    
  </connectionStrings>

  <appSettings>
  .................
  </appSettings>

  <location path="FederationMetadata">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>      
      <sessionState mode="Custom" customProvider="MySessionStateStore">
        <providers>
          <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="metalearningdev.redis.cache.windows.net" port="6380" accessKey="accesskeyhere" ssl="true" />
        </providers>
      </sessionState>
    </system.web>
  </location>

Within a method where I get the username of the logged in user I called the following method with two gets and two sets on the cache but looking at the portal logs I cannot see any calls being made:

public static void GetUserName()
    {
        ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("metalearningdev.redis.cache.windows.net,ssl=true,password=passwrod");

        // connection referes to a previously configured ConnectionMultiplexer
        IDatabase cache = connection.GetDatabase();

        // Perform cache operations using the cache object...
        // Simple put of integral data types into the cache
        cache.StringSet("key1", "value");
        cache.StringSet("key2", 25);

        // Simple get of data types from the cache
        string key1 = cache.StringGet("key1");
        int key2 = (int)cache.StringGet("key2");

        string userName = "";
        string domainStub = "";
        bool updatedLogin = false;
        string loginTime = "";
        //if (System.Configuration.ConfigurationManager.AppSettings["authenticationType"].ToString() == "ADFS")            
        if (System.Configuration.ConfigurationManager.AppSettings["platformType"].ToString() == "Cloud")    
        {
          //string userName = "";
          System.Security.Claims.ClaimsIdentity claimsIdentity = (System.Security.Claims.ClaimsIdentity)System.Threading.Thread.CurrentPrincipal.Identity;

          foreach (System.Security.Claims.Claim claim in claimsIdentity.Claims)
          {
              if (claim.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/windowsaccountname")
              {
                  userName = claim.Value;
              }
              else if(claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")
              {
                  userName = HttpContext.Current.User.Identity.Name;
                  domainStub = "FORMS";
              }
              else if (claim.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant")
              {
                  loginTime = claim.Value;
                  updatedLogin = true;
              }
          }

          if (userName.Contains("\\"))
          {
            string[] stringArray = userName.Split(new Char[] { '\\' });
            domainStub = stringArray[0];
            userName = stringArray[1];
          }              
          HttpContext.Current.Session["domainStub"] = domainStub;
          HttpContext.Current.Session["userName"] = userName;
          HttpContext.Current.Session["updatedLogin"] = updatedLogin;
          HttpContext.Current.Session["loginTime"] = loginTime;
          HttpContext.Current.Session["companyName"] = System.Configuration.ConfigurationManager.AppSettings["companyName"].ToString();
          //HttpContext.Current.Session["companyName"] = System.Configuration.ConfigurationManager.AppSettings["companyName"].ToString();
        }            
        else if (System.Configuration.ConfigurationManager.AppSettings["platformType"].ToString() == "internal")
        {
            userName = HttpContext.Current.Request.ServerVariables["AUTH_USER"];
            if (userName.Contains("\\"))
            {
                string[] stringArray = userName.Split(new Char[] { '\\' });
                domainStub = stringArray[0];
                userName = stringArray[1];
            }
            HttpContext.Current.Session["domainStub"] = domainStub;
            HttpContext.Current.Session["userName"] = userName;
            HttpContext.Current.Session["companyName"] = System.Configuration.ConfigurationManager.AppSettings["companyName"].ToString();
        }
    }

Can anyone see what I am doing wrong in order to get the session saved to the cache?

Jay
  • 3,012
  • 14
  • 48
  • 99
  • The code above worked as expected I just wasnt seeing any GET/SET counts for the session not sure if these are handled behind the scenes or whatever but the session is saving across the multiple instances. – Jay Jul 22 '14 at 13:45

3 Answers3

2

You can use CLI (Command Line Interface) of Redis and connect to a remote redis server:

Connecting to remote redis server

Then you can "GET" a value of your key and check if it was setted.

You can download CLI for windows in here:

https://github.com/MSOpenTech/redis

for Linux / Mac Os you can use apt-get / wget

Community
  • 1
  • 1
Thiago Custodio
  • 17,332
  • 6
  • 45
  • 90
1

Thiago Custodio is right. Adding to that:

Session is stored as hash inside redis.

  1. KEYS * => this will give you all available sessions. all sessions will have name like __Data
  2. HGETALL __Data => This will show all data for given session. This values are stored as byte stream so not much human readable, but keys are string.
RickAndMSFT
  • 20,912
  • 8
  • 60
  • 78
-1

The blog below included guidance on how to connect to the Redis cache that Session State creates using Redis CLI ...

http://blogs.msdn.com/b/webdev/archive/2014/05/12/announcing-asp-net-session-state-provider-for-redis-preview-release.aspx

Saurabh
  • 164
  • 2