Today, we are pleased to announce a preview release of ASP.NET Session State Provider for Redis. You can use it with your own Redis server or the newly announce Microsoft Azure Redis Cache (Preview).
What is Redis
Redis is an open source, BSD licensed, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets. It’s getting popular in the web development community as a session state store because of its simplicity, rich data structure support and outstanding performance.
Installing
You can download this preview release of ASP.NET session state provider for Redis () from NuGet gallery by running this command
Install-Package Microsoft.Web.RedisSessionStateProvider -Pre
Get Redis
Before using the session state provider for Redis, you need to (of course) get a Redis server. There are a lot of ways to get a Redis server depends on your OS and whether your app is in the cloud or on-prem. Today, I’m going to show you two:
In the cloud – Microsoft Azure Redis Cache (Preview)
The newly announced Microsoft Azure Redis Cache (Preview) provides your Redis host in Azure. It’s super easy to use. Just follow this get started article to get one in minutes. After it’s done, get hold of the host name and access key since we need to use them later.
On-prem – Redis on Windows
The Redis project doesn’t directly support Windows. However, Microsoft Open Technologies, Inc. develops and maintains a high quality Windows port. You can install it from NuGet, Chocolatey or download it directly from the project github repository. After the installation, you can find the following two .exe files that we are interested at:
- redis-server.exe: Run this .exe file and you will have a Redis server running on your machine.
- redis-cli.exe: We will use this as a command line tool later to check the data in your Redis server. Note: we’ll use it to check the data in Azure Redis Cache as well.
Create a simple project
To get started,
- Create an ASP.NET Web Application in Visual Studio.
- Add RedisSessionStateProvider NuGet package which will do the following:
- Add references to the ASP.NET session state provider for Redis assembly and its dependencies.
- Add the following configuration to system.web section in Web.config file.
- ]
- />
- –>
- <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="127.0.0.1" accessKey="" ssl="false" />
- </providers>
- </sessionState>
- If you are using Azure Redis Cache, modify host and accessKey with the values you get when you create the Redis Cache. If you are using local Redis server, leave them as it is.
- Add line 9 shown below to the Login method in AccountController.cs to add the login time to session.
- public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
- {
- if (ModelState.IsValid)
- {
- var user = await UserManager.FindAsync(model.Email, model.Password);
- if (user != null)
- {
- await SignInAsync(user, model.RememberMe);
- Session["loginTime"] = DateTime.Now.ToString(); // Add this line
- return RedirectToLocal(returnUrl);
- }
- else
- {
- ModelState.AddModelError("", "Invalid username or password.");
- }
- }
-
- // If we got this far, something failed, redisplay form
- return View(model);
- }
- Run the project.
- Run redis-cli.exe from command line to connect to the Redis server and check out the session data by running the following commands and you’ll see the session data is successfully stored in Redis. If you are running Redis server locally, you don’t need the -h (host) or -a (password) parameter. (You see the hex data because we convert the value into bytes before putting it into Redis). For more information about redis-cli, please refer to.
Protect your data Azure Redis Cache access key when using redis-cli.exe
When you use redis-cli.exe to connect to your Azure Redis Cache, since it doesn’t support SSL by default, the data and more importantly the access key are sent via TCP in clear text. To protect them, follow the instructions below to set up a SSL proxy on your machine for redis-cli.exe.
- Download and install stunnel.
- Open stunnel GUI Start from your start screen
- Click Menu –> Configuration –> Edit Configuration. This will open the stunnel configuration file.
- Go to the section named as “Example SSL client mode services” and add the following configuration.
- [redis-cli]
- client = yes
- accept = 127.0.0.1:6380
- connect = azrocks.redis.cache.windows.net:6380
- Click Menu –> Configuration –> Reload Configuration. This will let stunnel load the new configuration.
- Connect to your Azure Redis Cache using the following command
redis-cli.exe -p 6380 –a <your access key>
Now, you are having the TCP traffic from redis-cli.exe via a local SSL proxy provided by stunnel.
Configuration details
Now let’s look a little bit deeper into the settings you can use on this session state provider and how they will change its behaviors.
How to connect to Redis server
These are the settings that configure connections to Redis server:
- host: The IP address or host name of your Redis server. By default it’s localhost.
- port: The port of your Redis server. By default it’s 6379 for non-ssl and 6380 for ssl (if you are using Azure Redis Cache).
- accessKey: The password of your Redis server when Redis authorization is enabled. By default is empty, which means the session state provider won’t use any password when connecting to Redis server. If your Redis server is in a publicly accessible network, like Azure Redis Cache, be sure to enable Redis authorization to improve security.
- ssl: Whether to connect to Redis server via ssl or not. By default is false because Redis doesn’t support SSL out of the box. If you are using Azure Redis Cache which supports SSL out of the box, be sure to set this to true to improve security.
How session state provider should behave
throwOnError
When we talk to developers about the current available ASP.NET session state providers, one of the top complaints is that with the current available session state providers, if an error occurs during a session operation, the session state provider will throw an exception, which will blow up the entire application.
We want to address this in a way that it won’t surprise existing ASP.NET session state provider users and at the same time, provide the ability to opt-in the advanced behaviors. To do this, we introduced the following setting in this session state provider:
- throwOnError: Whether or not to throw an exception when some error occurs. The default is true.
As you can see, the default behavior will still throw an exception when some error occurs. This is consistent with the other ASP.NET session state providers we provide so there won’t be any surprise and your existing code will just work.
If you set throwOnError to false, then instead of throwing an exception when some error occurs, it will fail silently. If you need to check if there was some error and if there was one, what the exception was, you can check it using this static property
- Microsoft.Web.Redis.RedisSessionStateProvider.LastException
This is really cool because
- If you have some existing applications using some existing session state provider, you don’t need to change any code but get away from blowing up the entire application for free.
- You can explicitly check for errors if there were any.
retryTimeoutInMilliseconds
We also want to provide some retry logic to simplify the case where some session operation should retry on failure because of things like network glitch. At the same time, we also heard from developers that they want the ability to control the retry timeout or opt-out of retry entirely because they know retry won’t solve the issue in their cases. To do this, we introduced the following setting in this session state provider:
- retryTimeoutInMilliseconds: How long it will retry when an operation fails. Default is 0, meaning no retry.
If you set retryTimeoutInMilliseconds to a number, say 5000, then when a session operation fails, it will retry for 5000 milliseconds before treating it as an error. So if you would like to have the session state provider to apply this retry logic for you, you can simply configure the timeout. The first retry will happen after 20 milliseconds since that is good enough in most cases when a network glitch happens. After that, it will retry every 1 second till it times out. Right after the time out, it will retry one more time to make sure that it won’t cut off the timeout by (at most) 1 second.
If you don’t think you need retry (like when you are running the Redis server on the same machine as your application) or if you want to handle the retry logic yourself, you can just leave it to the default value 0.
Conclusion
We are really excited about this release. Give it a try and let us know what you think!
Join the conversationAdd Comment
Is this using the same "lock the session" for each request that the sql session provider does? Or will this allow more than one request to execute at the same time?
@Paul => It does same as sql session provider – lock the session for writing.
It's very great! I have some questions
How it saves items into redis? Based from HGETALL from screenshot each item saved as separate item in the same hashset? Does each item loads and serializes independently on others or all of them loaded in one request to Redis? What Redis provider it uses underhood? ServiceStackBookSlave or some custom implementations?
@ Sergey Litvinov
How it saves items into redis?
=> It saves single session into Redis as single hash.
For example, I have session with sesion id = "session-id-1". I have stored "key1 = val1" and "key2=val2" inside session. If you do HGETALL session-id-1_Data you will get both keys and values.
Does each item loads and serializes independently on others or all of them loaded in one request to Redis?
=> All values for given session will be loaded during fetch cycle of session inside GetItem/GetItemExclusive using HGETALL. But they are de-serialized independently one after another. But only those which are modified will be written back during SetAndReleaseItemExclusive.
What Redis provider it uses underhood?
=> StackExchange.Redis
This is really help full. I also refer if i get any problems
It misses a simple way to share a redis cache between multiple websites. A key prefix setting in the provider could resolve this.
@Joanna Robinson: Thank you, if you need any help or have any question post here.
@styx31: Can you explain some more about what you mean by "A key prefix setting in the provider could resolve this."
Where is the source code?
@Siddharth Chatrola Currently, the provder use the session id (random chars + data) as the RedisKey in the cache.
If two websites wants to share the redis cache instance for session storage, it could be better to prefix the session id with the applicationname attribute of the provider.
See msdn.microsoft.com/…/ms178587.aspx paragraph "ApplicationName".
The ability to provide a database id could be also great.
@ styx, @styx31 = Thanks for the feedback.
I am working on following two and will publish new NuGet and will let you know configuration details.
1) RedisKey as application name + session id.
2) Ability to provide a database id.
We already have such provider here:…/RedisAspNetProviders. What is the difference?
@alex-simonov: There are many differences in actual implementation but just to mention few bigger once SSL support, throwOnError, retryTimeoutInMilliseconds etc.
@Siddharth Chatrola, where is source code hosted?
@Siddharth Chatrola, I've opened dll with Reflector and found a bug. If I modify a state of a mutable object stored in session then these changes will not be saved in redis because this provider can not track changes of state of stored mutable objects.
@Siddharth Chatrola, also it's not a very good idea to store a "SessionStateActions" in session items.
This is awesome. Given that you are using StackExchange.Redis, how can the rich configuration of that package be made available? My primary interest is in setting up a fault tolerant Redis backend, either using Cluster, Sentinel or Twemproxy.
@alex-simonov: Thanks for pointing out the bug. I have fixed it and will be available in next release of NuGet. I don't understand reason of not putting "SessionStateActions" with actual data.
@Peter: "how can the rich configuration of that package be made available?" Can you explain bit more about what you mean by this.
@Siddharth Chatrola, "SessionStateActions" is not real data that users store in session, it is required only for managing a session state. User should not have access to read and modify "SessionStateActions".
@Peter, try using github.com/…/RedisAspNetProviders. With RedisAspNetProviders you have access to all configuration parameters of StackExchange.Redis via connectionString attribute.
Is there a way to prefix the keys,
It would be a great way to separate session keys from different applications, and also for maintainance.
The way it's usually done in Redis is using urn: namespace en.wikipedia.org/…/Uniform_resource_name
This is how the key looks like now:
skldfjgh8342o345o934ty493_Data
Here is what urn notation suggests:
urn:MyApp1Sessions:skldfjgh8342o345o934ty493
(Without the _Data postfix, it's redundant).
This is how the configuration section would look like:
WARNING! it's not a real config, just a future implementation suggestion.
<add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="127.0.0.1" accessKey="" ssl="false" keyPrefix="urn:MyApp1Sessions:" />
<add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="127.0.0.1" accessKey="" ssl="false" keyPrefix="urn:MyApp1Sessions:" />
Even if the keys are unlikely to collide, it would allow for sharing of the same redis instance for multiple appications and also add some maintainance capabilities.
For example – counting, enumerating, deleting or getting statistics for all the session keys for particular application.
Please consider adding this to the release.
>> Is there a way to prefix the keys?
You can do this with github.com/…/RedisAspNetProviders.
Proper link is github.com/…/RedisAspNetProviders
Hello, I need the ability to set an explicit key prefix, not derived. Harbour.RedisSessionStateStore allows me to accomplish this through the provider name.
@Greg, you can do this with keyPrefix attribute, see example here: github.com/…/RedisAspNetProviders.
Also it is possible to specify a database number.
@Siddharth Chatrola, basically, I need the ability to specify multiple redis nodes, and any other configuration parameters that StackExchange.Redis provides. The intention is to connect to a real redis cluster.
@alex-simonov, yes, tried that package, and it worked really well! I am now running session state on a real, 6 node Redis cluster, with both failover and sharding.
I have just uploaded new NuGet package 'RedisSessionStateProvider 0.1.0.375-Pre' which contains bug fix found by @alex-simonov. I have also added two optional attributes 'databaseId' and 'applicationName'.
@styx, @styx31,
databaseId = this will allow you to choose database inside redis server
applicationName = this will work as prefix of the key inside redis which will allow redis server to be shared between applications
@Is there a way to prefix the keys?
'Without the _Data postfix, it's redundant' => can't do this. there is something like *_Lock is also used for locking mechanism of session state provider. So _Data and _Lock is the way to differentiate them. You never see _Lock because session state provider acquires lock during GetItemExclusive and releases during SetAndReleaseItemExclusive or ReleaseItemExclusive.
Also try to take advantage of features like 'throwOnError' and 'retryTimeoutInMilliseconds'.
Let me know if you have other suggestions or want to see few enhancements.
Are steps taken to ensure synchronous replication to slaves? I'm concerned about corrupted sessions in the case of a master->slave failover.
@ Rapzid
We can't always guarantee that you won't loose data during failover. Imagine you just write data in Redis master and it failed now. Failover happened and slave don't have this latest data. Failover is something concept of cache and not session state provider.
Is there any reason redis-cli wont show me the data in the hash's keys?
if i add 1000 items to session i can query keys via .net Session["keyname"] returns me the correct values. I can see the hash in redis and it has 1000 items. if i do a hkeys it returns the keys if i do a hlen it says 1000, but if i try and do a hget or a hvals, redis-cli doesnt return any values?
Is there an equivalent to Session.Abandon() that we used with our previous session state store provider to clear session state?
@AC
You can use Session.Abandon() will behave exactly same as it behaves with normal session. All things that asp.net standard specifies about session are valid.
I would like to be able to specify atleast the Host, Port and AccessKey settings in the Azure Role Enviroment Configuration Settings instead of in the web.config. Do you think you can implement that?
What about the session time out how does it work as soon it times out it will clear all used keys from the redid server to free up the memory of the redis server? or do we need to do this manually and have the timeout of the session be in sync of the redis server timeout?
@J K
Session timeout is basically expiry on key inside redis-server. if session gets expired than redis will clean this session by itself as the key is expired. you don't have to do anything to clear it. Redis will clear it automatically.
@Zims
I didn't understand your question completely. I think you are saying you want to use configuration from somewhere else rather than web.config?
It appears that in some instances, Session.Abandon() call is not removing the session data. I am not sure if the RemoveItem method was implemented correctly.
Here is what I see from MSDN article.
"When the Abandon method is called for a session, the data for that session is deleted from the data store using the RemoveItem method. Otherwise, the data remains in the session data store to serve future requests for the session."
And here is reflected code from provider
public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
{
try
{
if (RedisSessionStateProvider.LastException != null)
return;
// rest of the code.
Question: why do you care about lastexception when the RemoveItem is trying to delete session data? LastException might have happened for some other reason?
@Kiran:
When you call Session.Abandon() it will call following methods in sequence.
1) GetItemExclusive
2) RemoveItem
3) EndRequest
When GetItemExclusive fails it logs this exception in our LastException property. Now, it will not run RemoveItem. Suppose if we run RemoveItem and it failed than we will never know where did the exception occurred first. Using LastException you can find if the operation was successful or not and if not successful what went wrong.
Hi,
The NuGet package installed fine and added the following to the web.config of my azure cloud project:
<sessionState mode="Custom" customProvider="MySessionStateStore">
<providers>
<add name="MySessionStateStore"
host=<snip>
port="6379"
accessKey=<snip>
<!– <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="127.0.0.1" accessKey="" ssl="false" /> –>
</providers>
But when I launch, the web server complains that there isn't a "type" in the provider. So I put this in:
type="Microsoft.Web.Redis.RedisSessionStateProvider"
from the other example, but then I get this error:
Could not load type 'Microsoft.Web.Redis.RedisSessionStateProvider'.
Should I be putting in that type in the provider? Should I use another one?
Cancel my question, NuGet doesn't seem to install everything properly to a .NET 4.0 project. I had to upgrade to 4.5 in order to get the type to work.
@alan,
Yes, right now it works fine with just .net 4.5. We have created nuget for .net 4.0 as well but didn't pushed changes in production yet. you will get it in few days.
It is possible to specific multiple hosts in the sessionState config so that I can achieve high availability?
I believe that StackExchange.Redis supports this by comma delimiting the hosts…
github.com/…/Configuration.md
Many thanks
@PaulR
Use Azure Redis Cache (Standard) which by default provides High Availability.
Siddharth, thanks for the response.
However, my project is self hosted, not using Azure.
I will have one or more redis servers (separate from the web servers) and need to be able to specify these servers in the SessionState configuration. Currently it looks to me like I can only add one state server here…
<add name="MySessionStateStore"
host = "127.0.0.1" [String] <— *** ability to add multiple hosts here? ***
port = "" [number]
accessKey = "" [String]
ssl = "false" [true|false]
throwOnError = "true" [true|false]
retryTimeoutInMilliseconds = "0" [number]
/>
Please advise.
Many thanks.
New package for session state provider is out. (0.2.0-Pre-54)
We are using signed version of StackExchange.Redis (SE.Redis.StrongName). It includes two new parameters that you can configure from web.config.
connectionTimeoutInMilliseconds: ConnectTimeout inside stack exchange
operationTimeoutInMilliseconds: SyncTimeout inside stack exchange
@PaulR
I have to check with couple of people for allowing multiple hosts.
I get the following error with the latest NuGet package. It seems to not be referencing the .StrongName version. If I install the StackExchange.Redis package I get a similar error.
Could not load file or assembly 'StackExchange.Redis, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c219ff1ca8c2ce46' or one of its dependencies. The system cannot find the file specified.
I'm also getting the error: 'Could not load file or assembly 'StackExchange.Redis, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c219ff1ca8c2ce46' or one of its dependencies.'
Maybe a wrong reference, because of the .StrongName?
@Keith @Peter Sinke
There is some issue with latest StackExchange.Redis.StrongName.1.0.320. Use StackExchange.Redis.StrongName.1.0.312 and this should work fine.
@Siddharth
Thanks! That did the trick.
Not sure if I accidently changed something else, but ever since yesterday's update, my test env. takes 15 seconds for every request AND my sessions are being reset for every single page request.
Disregard above about requests being slow and session resetting… What's really going on is that a RedirectToAction(…) now obliterates any Session["mySessionVariable"] set in the original action. It appears the session itself is being retained? Still researching….
@Keb
I can confirm,
We had exactly the same in our environment. Since some moment, Every request takes additional 5 seconds (time in retryTimeoutInMilliseconds). ping to Redis server <1ms, Redis answers ok via console.
StackExchange.Redis.StrongName is fixed in version 1.0.322. Microsoft.Web.RedisSessionStateProvider is updated to use this package (assembly name was modified inside StackExchange.Redis.StrongName). Start using Microsoft.Web.RedisSessionStateProvider.0.3.0-Pre-63 with latest stack exchange.
@Tymur @Keb
Please try your use case with latest package and let me know if issue still persist. If issue is still there please provide reproducible test.
Brilliant! Works so far… will keep you posted. =)
RedisOutputCacheProvider is out (…/0.3.0-Pre-67). Its MSDN page will be out shortly.
Thanks for nice post!
It is possible to share sessions of two IIS applications with Redis SessionState provider?
Can I get it to serialize using the DataContractSerializer?
Fix this bug please!
social.msdn.microsoft.com/…/random-nullreferenceexception-with-microsoftwebredisredissessionstateprovider.
This provider doesn't allow passing multiple redis connections. Could you let the host to accept a comma delimited redis hosts?
@Siddharth Tried to use on production server. System.TimeoutException: Timeout performing EVAL, inst: 1, queue: 1, qu=0, qs=1, qc=0, wr=0/0, in=0/0. Had to go back to the Standard .Net Sesson provider. Any ideas?
@Stas: It is possible to share sessions of two IIS applications with Redis SessionState provider?
=> This is more of IIS and ASP.NET question. Nothing different for Redis session state.
@mms: social.msdn.microsoft.com/…/random-nullreferenceexception-with-microsoftwebredisredissessionstateprovider
=> Thanks for pointing out it. I have fixed and it will be available in next release very soon.
@mms:.
=> I have to look into this.
@chand: This provider doesn't allow passing multiple redis connections. Could you let the host to accept a comma delimited redis hosts?
=> I am not 100% sure I understand this correctly. Can you explain bit more?
@Mike: Tried to use on production server. System.TimeoutException: Timeout performing EVAL, inst: 1, queue: 1, qu=0, qs=1, qc=0, wr=0/0, in=0/0. Had to go back to the Standard .Net Sesson provider. Any ideas?
=> Try to use below two parameter for resolving this.
connectionTimeoutInMilliseconds = "5000" [number]
This is just a wrapper around “ConnectTimeout” parameter of StackExchange.Redis.StrongName.
operationTimeoutInMilliseconds = "5000" [number]
This is just a wrapper around “SyncTimeout” parameter of StackExchange.Redis.StrongName.
Defaults are as follows,
ConnectTimeout = 5000 milliseconds
SyncTimeout = 1000 milliseconds
@Siddharth: How many concurrent users it can support at the same time.
Is there any load test results available for this.
For others that are interested in serializing using the DataContractSerializer. I was able to derive from the RedisSessionStateProvider and override GetItem, GetItemExclusive and SetAndReleaseItemExclusive, replacing each non-value-type object in session state with my own surrogate serializable object (a byte[] internally) immediately after retrieving and immediately before setting the session state. I can serialize using whatever method I choose. Probably adds a little overhead, but required to avoid a breaking change without having to touch the existing classes.
I'm getting these exceptions randomly and cannot determine cause or resolution.
This is great! We want to experiment with this, but were curious as to when we might see this as officially released not just in preview. Is there a date planned already?.
However, the sessionState section is not configurable/overridable in the Azure Portal, so the Redis connection string must be deployed with the web.config. This breaks our nice-and-simple deployment: we have to do a web.config transform for every environment.
It would be much better to be able to specify a connectionStringName instead of having to duplicate the actual connection information in this nonstandard place.
Will the Session_OnEnd event be called when the sessions is abandoned explicitly or if it times out?
Hi,
I'm getting Timeout errors too. Works fine in production but when debugging locally I'm consistently getting "Timeout performing EVAL, inst: 0, queue: 5, qu=2, qs=3, qc=0, wr=1/1, in=0/0 "
web.config contains retryTimeoutInMilliseconds="5000" connectionTimeoutInMilliseconds="5000"
Any assistance would be appreciated as this is a real pain!
Thanks
Mat
Getting this exception when the user makes the very first call.Delete all session cookies and make a request to the server and this exception is thrown.I used the preview release.)
We have released a new Nuget package (RedisSessionStateProvider 0.4.0-Pre-121). You will be able to set any settings using app setting in web role in azure. I hope this is helpful. Let me know if you have any other question.
Web.Config
=========

1) @roy.subhrajit: @Nathan DUnn: Exception: System.NullReferenceException: Object reference not set to an instance of an object.
=> This bug has been fixed in this new version (RedisSessionStateProvider 0.4.0-Pre-121).
2) @chand:
=> session state provider is not providing this as of now as azure redis cache is doing failover in backend by itself and used don't have to know about it.
3) @Sharath Satish: This is great! We want to experiment with this, but were curious as to when we might see this as officially released not just in preview. Is there a date planned already?
=> Sometime in Fall 2014.
4) @MaartenS:….
=> The above app setting related options will solve your problem.
5) Will the Session_OnEnd event be called when the sessions is abandoned explicitly or if it times out?
=> Can you elaborate?
6) @mAT: I'm getting Timeout errors too. Works fine in production but when debugging locally I'm consistently getting "Timeout performing EVAL, inst: 0, queue: 5, qu=2, qs=3, qc=0, wr=1/1, in=0/0
=> This happens if there is a long running operation in redis queue which is causing operations after it in queue to timeout. This is basically Redis question and nothing specific to session state provider.
Have posted a question on StackOverflow about this. stackoverflow.com/…/microsoft-asp-net-redis-session-state-throws-an-exception
I keep getting NullReferenceExceptions after win forms login and I can't figure out why. The SO question has stack trace and config. Any help would be greatly appreciated.
"session state provider is not providing this as of now as azure redis cache is doing failover in backend by itself and used don't have to know about it."
We are using this provider in a non azure websites.
I am not sure how the following scenario works without provider knowing about all the nodes in the cluster.
SessionProvider is configured to use single Redis host.
Website goes down.
Redis primary goes down.
Website comes back. But Redis primary is still down.
How does the website know about where to connect without the knowledge of secondary node?
Following line of code solves the above scenario.
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("server1:6379,server2:6379");
After changing to SessionProvider to use RedisSessionProvider,
Session.TimeOut property is returning time in seconds. Default provider returns time in minutes.
Now logic that depends on Session.Timeout value is breaking.
@chandmk:.
@chandmk: "Session.TimeOut" Found the bug and solved it, will be releasing new NuGet package in some time. I am wondering how come it was working till now. This bug was there till its first version.
@Rikard: Please contact us on AzureCache@microsoft.com.
Will the Session_OnEnd event be called when the sessions is abandoned explicitly or if it times out.
When the session reaches the timeout will the Session_OnEnd event in the GLobal.asax file be called. Will it be called if I call Session.Abandon()
@Abhishek Shah
Session_OnEnd event be called as per ASP.NET guideline. Redis session state provider should behave exactly same as other session state provider.
If it behaves any other way let me know here and I will fix it. You can also report any bug by emailing us at AzureCache@microsoft.com.
can we haz the code? i want to change the redis clientto csRedis.
It would be really great to be able to just use a connection string name rather than having to add the key in the provider itself. Saves having to use xml transforms for both connection strings and the provider.
Thanks
@Cam,
You can use Azure app settings to provide all parameters. Then in web.config you have to just specify the name of key and it will fetch its value from app settings.
@siddharth you said: ."
You answered the scenario of website is up, primary goes down and redis automatically fails over to secondary.
What about the following scenario?
SessionProvider is configured to use a single host address.
Website goes down.
Redis primary machine goes down.
Website comes back. But Redis primary is still down.
How does the website know where to connect when its only known redis server machine is disappeared?
.
@siddharth, what if I am not using azure redis cache? I like to host redis on my own windows server with a fail over node. I thought this is exactly why stackexchange connection multiplexer allows me to specify more than one node in the connection strings.
@Siddharth It is great that you implementet a feature where we can stor the settings in AppSettings and not only web.config. I have tested this and can not get it to work. I am running a website as a Azure Worker Role and I tried to put the settings in the ConfigurationSetting for the Azure Role.
Is that supposed to work or does this feature only works with Azure WebSites AppSettings?
@Zims:
It will work only if you put it inside "app settings" not in ConfigurationSetting.
Go to "your website" -> CONFIGURE tab -> app settings section. (put your settings here)
@Siddharth, I Think I don't follow you 🙂
I am using a "Azure Web Role" for my website, not a "Azure Web Site".
When I select my Web Role and goes to the CONFIGURE tab I am only able to add/change my "ConfigurationSettings" from the .cscfg file, not any app settings? I have tried to add the settings there but that does not work.
I belive to be able to access the settings in the CONFIGURE tab for the WebRole you must use RoleEnviroment.GetConfigurationSettingValue()?
I found a small problem.
In my website we set the Session Timout from code, not from web.config. We do that in the global.asax and SessionStart. There we do Session.Timout = XX;
This works fine when using the InProc session state provider, but when using this provider it does not work, it allways fall back to 20 minutes or the value specified in web.config.
I found a bug… (in version 1.0.0)
It does not work when you request a read only session.
ReleaseItemExclusive is called with lockId of null, which throws a NullReferenceException down the line…
@Cillie:
I am not able to reproduce the issue. I see lockId is being passed valid value. If you can send us reproducible app on AzureCache@microsoft.com than we can take a look.
@Zims: Sorry for the confusion. Yes, in web role there is no app settings. Session state do not read from config settings. You can do something like this (anuchandy.blogspot.com/…/changing-webconfig-file-deployed-on.html) to modify web.config on the go.
@Siddharth or you could check if "RoleEnvironment.IsAvailable" is true and then get the settings from the Roles ConfigurationSettings instead of AppSettings 🙂
@Siddharth, regarding my problem with setting Session.Timeout = XX; from code I forgott to mention that I use version 1.0.
I can't find where I can submit bugs for this provider but I there a problem with logging.
Both Providers rely on LogUtility to log Info, Warning & Error messages (thanks to ILSpy)
Here is the LogError method. Nothing is returned, causing several troubles when debugging.
// Microsoft.Web.Redis.LogUtility
public static void LogError(string msg, params object[] args)
{
if (args.Length <= 0)
{
return;
}
string.Format(msg, args);
}
@Zims I have same problem. Session.Timeout = XX (in code) does not change life time of key in redis. And after it changes to default value (20 mins).
Anyone has solved this problem. Because I need to change session timeout at life time.
@SiddharthChatrola, the Session_OnEnd events still don't fire.
Any ideas?
Everywhere that I searched says that "must use inproc", or "must have something in the session_onstart"..
Using: MVC5, Microsoft.Web.RedisSessionStateProvider v4.0.30319
We're getting a null reference exception reproducible by the following:
1) Client includes a session ID cookie in the request, and
2) Redis does not have any session (key) matching the session ID client has sent.
—
Object reference not set to an instance of an object.
mscorlib
GetType
at System.Object.GetType()
at Microsoft.Web.Redis.StackExchangeClientConnection.Eval(String script, String[] keyArgs, Object[] valueArgs) in c:TeamCitybuildAgentworkbe3588ff188ebfd1srcCacheProviderSharedStackExchangeClientConnection.cs:line 79
at Microsoft.Web.Redis.RedisSessionStateProvider.ReleaseItemExclusive(HttpContext context, String id, Object lockId) in c:TeamCitybuildAgentworkbe3588ff188ebfd1srcCacheProviderRedisSessionStateProviderRedisSessionStateProvider.cs:line 329
at Microsoft.Web.Redis.RedisSessionStateProvider.GetItemFromSessionStore(Boolean isWriteLockRequired, 256
at Microsoft.Web.Redis.RedisSessionStateProvider.GetItem 168
at System.Web.SessionState.SessionStateModule.GetSessionStateItem())
—
We're using RedisSessionStateProvider 1.0.0.147 (from nuget) with StackExchange.Redis.StrongName 1.0.333.0. I've read that earlier versions had problem storing NULL objects. We're *not* storing any null objects.
Redis session state will work properly if client removes the invalid session ID from cookie.
We're getting a lot of these due to key eviction policies on the Redis side. Is there any fix/workaround?
There is a third condition to reproduce the above error:
3. The ASP.NET page contains EnableSessionState="ReadOnly".
The above exception does /not/ occur for pages with EnableSessionState set to true or false.
@Zims
1) Checking "RoleEnvironment.IsAvailable": I will implement this as soon as I get time.
2) Session.Timeout = XX: I am working on this bug, It will be out soon.
@Cybermaxs
Logging will be available in some time. Actually, you see logging that way because you have release version and not debug version. I will start working on logging feature soon enough.
@MaDOnos
Session.Timeout = XX: I am working on this bug, It will be out soon.
@Gabriel Melo
Sorry! if I said otherwise earlier. msdn.microsoft.com/…/ms178583(v=vs.90).aspx
Session_OnEnd events is only valid in inproc. For redis session state provider we do not support it.
@Sunny
If you can generate reproducible application and send me on AzureCache@microsoft.com than it will be very helpful.
@Zims,@MaDOnos
Fix for bug "Session.Timeout = XX is available in…/1.1.0
@Siddharth, Thanks for the Session.Timeout fix and thanks for implementing "RoleEnvironment.IsAvailable" in future version!!
Hello , Microsoft.Web.RedisSessionStateProvider how to achieve load balancing ?
Their structures Redis Server。
Hi there
We are having an issue with timeouts when storing Session State using Redis cache. We find that having deployed our production application we run fine for between 3 – 4 hours and then see a big spike in errors similar to this "System.TimeoutException: Timeout performing EVAL, inst: 230, mgr: Inactive, queue: 34, qu=0, qs=34, qc=0, wr=0/0, in=4995/0". The errors escalate and eventually cause our app to become unresponsive.
There are full details here of the things we have tried so far here – social.msdn.microsoft.com/…/timeouts-when-storing-sessionstate-in-azure-redis-cache
At present we have had to roll back the use of Redis cache in production due to the instability we are seeing. If anybody has any suggestions on things we should check out in detail or what might be causing the issue it would be great to hear them.
Thanks
Hello,
How can I use configure Redis Sessionstate provider to use settings (host, port etc) from AppSettings in Web.config ?
In Azure Websites you typical want to store the settings in the portal.
@Azure websites appsettings: You can use app settings as follows. Put actual values in AppSettings and then in web.config use AppSettings key.
in Web.Config
========

@ Justin Hewitt
First thing you can try to do is update to RedisSessionStateProvider 1.1.0.
Increase following 2 timeouts in web.config:
retryTimeoutInMilliseconds = "50000" (50 sec)
operationTimeoutInMilliseconds = "10000" (10 sec)
This might help you here. It looks like your operations are failing because there are many operation inside queue.
EVAL, inst: 121, mgr: Inactive, queue: 399, qu=0, qs=399, qc=0, wr=0/0, in=65536/0".
This means there are 399 operations in queue waiting for response from redis-server.
We've just started using this and found it incompatible with the version of redis we had running.
I believe running anything newer than 2.6 will work, but 2.4 does not.
@Siddharth I'm facing the same issue as @chandmk.
We have an on-premise Redis on Windows, placed in a Master/Slave config.
But there doesn't seems to be a way to add multiple host-names in the "host" parameter.
Example:
<add name="RedisSessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="REDISCACH-SVR01:6979;REDISCACH-SVR02:6379" />
Gives a "It was not possible to connect to the redis server(s)".
Can you please add support for this? StackExchange.Redis supports this connectionstring fine.
Hello,
I have some problems
If a request A and B initiate a request in sequence , each request adds a value to different keys in the session, the B request to finish before the request A, the values that the request wrote in the session before the request B finished are lost .
Here is link to download an example , make clear Session and then Run A, B , C, note that the value of the returns null.
drive.google.com/…/view
What do I do?
Thank you
From where can i get source code for Microsoft.Web.RedisSessionStateProvider
Yes, with the rest of the stuff being put up on github this seems like a perfect candidate.. Would be nice to get the bulk of the community working on the same Redis session state provider. Are there plans to put it up there with the other azure-sdk projects?
Siddharth, can we get a simple string "options" setting made available on the provider config that if present takes precedence over the existing properties? This would give everyone the power options they need for master/slave/sentinel setup as well as the other unexposed options.
Add the property then modify the StackExchangeClientConnection constructor to be something like:
ConfigurationOptions configurationOptions = null;
string options = configuration.Options;
if (!String.IsNullOrEmpty(options))
{
configurationOptions = ConfigurationOptions.Parse(options);
}
else
{
configurationOptions = new ConfigurationOptions();
// do existing work here, set host, port, password, ssl, etc
}
// set multiplexer and connection as normal
+ one more vote for putting the source on github or similar.
@David Brink: we have implemented "optionsString" settings feature requested by you. But before releasing it to all I wanted you to test it and send me feedback. Can you send me your email so that I can send you local NuGet package that you can test your app with and give me feedback.
@Job: Once this feature is out it will solve your problem as well.
@Taher, @Greg: Code for Session state provider will become available on GitHub at some point. But right now we don't have cycles to do that.
Lock mechanism exist on both provider and session module (IIS Session Module). You can develop custom session module, but you still need provider without locking or You can develop custom provider without locking but you still need IIS session module and it is not so simple to implement at that level.
The Solution is [UnlockedStateProvider][1] [aka Unlocked]
[1]: github.com/…/UnlockedStateProvider
Follow the white rabbit 😛 (Check the demo project, it explains everything.)
RedisSessionStateProvider 1.2.0 is out and it contains few bug fixes. It also contains a new feature that allows you use ‘connectionString’ to take advantage of all parameters provided by StackExchange.Redis. For more details look at comments in web.config that is added by RedisSessionStateProvider 1.2.0.
Either use 'connectionString' and provide all parameters as string OR use 'host', 'port', 'accessKey', 'ssl', 'connectionTimeoutInMilliseconds' and 'operationTimeoutInMilliseconds'. Other parameters like 'throwOnError','retryTimeoutInMilliseconds','databaseId' and 'applicationName' can be used with both options.
Let me know if there is any other confusion.
Same comment as @Job.
I'd like to see a way to specify a master/slave (read-only) setup to distribute load, as seen in StackExchange.Redis:
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("server1:6379,server2:6379");
I think putting an nginx in-front of redis would make more sense (redirect read traffic, handle failover), but this is nice to have in the interim.
A connectionString parameter is a good improvement in version 1.2, but it's confusing that it does not accept the name of an existing connection string under <connectionStrings>. It does accept the name of an AppSetting however, so now there is only one duplicate configuration item in our configuration, which is better than is was before.
I decided to switch over from Harbour.RedisSessionStateStore 1.3.0 as this driver was more resilient with the retries and other timeout settings.
It appeared to be working fine, but then we started noticing that some complex and large datatypes, eg. List<List<SomeObject>>, were coming back null after they had been set in Session["key"].
These were never an issue with the Harbour.RedisSessionStateStore 1.3.0 driver, which had been running for about a year. InProc also worked fine (but that's not a real test).
The Session["key"] is stored in a controller, for a PartialViewResult action. When it gets to the PartialView page, its fine. Another control on the page is asking for this object, the Session["key"] is fetched in its BaseController, and consistently has the value of null when a value was just set.
I've tried playing with all the settings and making it as generous as possible, this is what it finally looked like, and it still didn't work:
<sessionState mode="Custom" customProvider="AppRedis" timeout="20" cookieless="false" compressionEnabled="false">
<providers>
<add
name="AppRedis"
type="Microsoft.Web.Redis.RedisSessionStateProvider"
host="redis.company.local"
port="6379"
accessKey="password"
ssl="false"
throwOnError="false"
retryTimeoutInMilliseconds="20000"
databaseId="1"
applicationName="AppName"
connectionTimeoutInMilliseconds="20000"
operationTimeoutInMilliseconds="20000" />
</providers>
</sessionState>
Any help in understanding the issue would be appreciated. I like the features of this driver, but if it inconsistently stores the data, we can't use it. At the moment we have to revert back to Harbour.RedisSessionStateStore 1.3.0.
I did all the steps from this tutorial
–> Created new MVC Web Site
–> Added Nuget package
–> Modified the Web.Config to reflect my Azure Redis
But, everytime i try to run my project, i get the following error message :
It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING
what im a missing?
thanks
Thanks for the recent updates!
Are there any release notes for todays release?
@sonjz: 'connectionString' will solve your problem.
@MaartenS: Let me know what is confusion and I will try to resolve it.
@Jason Huggins: I tried List<List<string>> and it worked fine. I can solve the bug if you can provide reproducible app. May be 'SomeObject' is not serializable.
@Eric Dugal: You have to set your cache credentials in web.config. By default azure cache has non-ssl port (6379) blocked (you can unblock it through portal or powershell). So provide ssl=true.
@Job: There isn't any change in this release. Its just that critical bug in StackExchange.Redis.StrongName was fixed and we wanted our customer to move to latest version of StackExchange.Redis.StrongName.
Hi,
We are saving viewstate in session and we running into that issue:
stackoverflow.com/…/microsoft-asp-net-redis-session-state-throws-an-exception
Any chance it will be fixed?
@Witold: If you can provide me a small app (to AzureCache@microsoft.com) then I can fix it fast. I think you are getting error when you try to insert "Null" as key?
@Siddharth Chatrola:
We are only doing this:
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
and sets RedisSessionStateProvider 1.5.0 as session state provider.
I don't know what asp.net is setting then. Is it trying to set "Null" as key. It works for github.com/…/RedisAspNetProviders.
@Witold
I tried just same thing but didn't get any error. Even I can see data in redis using redis-cli also.
redis 127.0.0.1:6379> keys *
1) "/_n1hkhjkbgag2a1f3pvve4kya_Data"
2) "/_n1hkhjkbgag2a1f3pvve4kya_Internal"
redis 127.0.0.1:6379> hgetall /_n1hkhjkbgag2a1f3pvve4kya_Data
1) "__VIEWSTATEQUEUE"
2) "x00x01x00x00x00xffxffxffxffx01x00x00x00x00x00x00x00x04x01
x00x00x00x18System.Collections.Queuex06x00x00x00x06_arrayx05_headx05_
tailx05_sizex0b_growFactorb_versionx05x00x00x00x00x00bbbbbtx02x
00x00x00x00x00x00x00x01x00x00x00x01x00x00x00xc8x00x00x00x01x
00x00x00x10x02x00x00x00 x00x00x00x06x03x00x00x00!__SESSIONVIEWSTA
TE8d21377b2573762rx1fx0b"
3) "__SESSIONVIEWSTATE8d21377b2573762"
4) "x00x01x00x00x00xffxffxffxffx01x00x00x00x00x00x00x00x0cx02
x00x00x00MSystem.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f
7f11d50a3ax05x01x00x00x00x12System.Web.UI.Pairx02x00x00x00x05Firstx0
6Secondx02x02x02x00x00x00x06x03x00x00x00t253599918tx04x00x00x00
x01x04x00x00x00x01x00x00x00ntx05x00x00x00x04x05x00x00x00x1c
System.Collections.ArrayListx03x00x00x00x06_itemsx05_sizeb_versionx05x0
0x00bbtx06x00x00x00x02x00x00x00x02x00x00x00x10x06x00x00x00
x02x00x00x00bbx00x00x00x00tax00x00x00x01ax00x00x00x01x00x0
0x00tbx00x00x00nx01bx00x00x00x01x00x00x00ttx00x00x00nx01
tx00x00x00x05x00x00x00tnx00x00x00x04x00x00x00x04x00x00x00x1
0nx00x00x00x04x00x00x00tx0bx00x00x00x06x0cx00x00x00 52ea37f238
cd40c8937069c496c72066trx00x00x00x06x0ex00x00x00x00x05x0bx00x00x
00x1bSystem.Web.UI.IndexedStringx01x00x00x00x06_valuex01x02x00x00x00
x06x0fx00x00x00x0f__AntiXsrfTokenx01rx00x00x00x0bx00x00x00x06x10
x00x00x00x12__AntiXsrfUserNamex0b"
redis 127.0.0.1:6379>
I can try to serialize and send you what is passed to SavePageStateToPersistenceMedium when it is throwing exception so you could try to reproduce this. We really would like to use ASP.NET Session State Provider for Redis but this error preventing us from doing this. Can you please help?
Thanks.
@Witold
I would be happy to help you. Just provide me small app that can reproduce the problem. You can send us app on AzureCache@microsoft.com.
@Siddharth Chatrola
I have checked that more precisely and unfortunately indeed we are setting null keys is some existing legacy part… eh. I will try to fix that but just for curiosity: will you support such case as it is for example for Sql Server: support.microsoft.com/…/321023 ?
just do a stress test. Find out it only support max to 3500 session only.Beyond it will crash anyone encounter this issue
Hi there,
In our application, we occasionally get an issue with responses never coming back so the page take forever to load. Initally thought the server was somehow blocked and thus not responding, however, I found this happens to only one user session. A user with a different session ID does not have problem contacting the server even when another user cannot get a response. With the monitor command, I can see the SessionStateProvider repeatedly calling the redis server a few times per second nonstop.
"SETNX" "ApplicationName_SessionID_Write_Lock" "12345679012345678"
GET "ApplicationName_SessionID_Write_Lock"
HGET "ApplicationName_SessionID_Internal" "SessionTimeout"
If we manually remove the WriteLock outside of our application, everything goes back to normal.
Any idea what can possibly cause this to happen?
Thank you.
I'm having session timeout every time.
Session timeout is 30 minutes. But independente user's posts, it'll be expired in 30 minutes -.-
CAN YOU FIX THIS??????????????????????
@alan: We didn't encounter such problem in our stress test. Can you send us test app at <AzureCache@microsoft.com> so we can debug this further?
@joseph.bi: Every request will fetch session from redis in start phase using method GetItemExclusive() and at end of page execution it saves session back to redis using SetAndReleaseItemExcuusive(). Now it is possible that same user can send multiple request to server at same time so we required locking mechanism. More details can be found at msdn.microsoft.com/…/ms178587(v=vs.140).aspx
@Henrique: I couldn't understand the problem. Can you please provide more details? If possible send reproducible app to AzureCache@microsoft.com
Thanks for your reply, Siddharth. We know for a fact that there is an exclusive lock between request and response. Our situation is in fact occasionally the lock cannot be released. This happens in my development environment, and we are concerned this will happen in other environments. I noticed the expiry for an exclusive lock is 120,000 seconds, meaning when this rare situation happens, it will block the particular user session for about 33 hours. Is it an intended expiry?
Is there anything that can possibly stop the lock being released?
I hadn't had this issue when we used StateServer.
Same issue as joseph.bi, we read from session directly in a view(MVC 4 application) in quick succession and the lock is never released.
First call acquires the session lock with GetItemExclusive , second call does the same, page continues to render and SetAndReleaseItemExclusive is called but never releases the lock.
Subsequent calls to GetItemExclusive for that session id stall since the lock can not be acquired and the commands that joseph.bi observed can be seen using monitor on the Redis box(we run 2.8.4)
We previously used the appfabric session state provider and it did not behave like this. We are investigating but can confirm that this is an issue, any help you can provide would be helpful
The timeout value doesn't seem to work in version 1.6. No matter what it's set it to, it always stays at its default value of 20 minutes, i.e. Session.Timeout always returns 20.
I've reverted back to 1.5 for now which doesn't seem to have this problem.
@Siddarth
I've seen the mention of ConfigurationOptions possibly being integrated, I'm trying to setup the ConnectionMultiplexer, for the master/slave setup.
Thanks!
We are also seeing the same issue as joseph.bi with occasional rapid blasts to Redis from the session provider and particular sessions being stuck for minutes at a time. Why is it getting stuck in this state and even if it is stuck why is it not timing out as it should according to retryTimeoutInMilliseconds?
I'm also having the same issue as joseph.bi and the others. Everything looks as working correctly for a while but then the processes get stuck, waiting forever to get a response. The momeny I flush the redis db and the lock is gone, everything starts loading again.
@Mark
Can you provide repro for this issue?
@Dvorac
Didn't understand your question?
@joseph.bi
@XhantiB
@Alec
@Murat Boduroglu
I am talking to Alec about this on email thread. I will try to resolve it as early as possible. For fast reply please email to AzureCache@microsoft.com.
When we create lock during GetItemExclusive, we set lock timeout to “HttpRuntimeSection.ExecutionTimeout”. In simple ASP.NET application this is available inside web.config under “system.web/httpRuntime”.
If this is not provided then by default ASP.NET provides 110 seconds as HttpRuntimeSection.ExecutionTimeout. So your lock will be released automatically by redis after this time. Is by any chance this valued is set to very large value?
@Siddharth Chatrola
Yes, in my case this was a very high number, most probably because the application got some non queued processes that might take a long time.
Lock can get stuck if your timeout is very large. This is not timeout that you set as session state provider parameters (it is not retryTimeoutInMilliseconds or connectionTimeoutInMilliseconds or operationTimeoutInMilliseconds). This is “HttpRuntimeSection.ExecutionTimeout” that you can set in wen.config inside system.web section like follows.
<configuration>
<system.web>
<httpRuntime executionTimeout="10"/>
</system.web>
</configuration>
Your lock can be stuck if this is very large.
We did a bug fix about deleting lock key at end of SetAndReleaseItemExclusive which was somehow missed.
We have also released new version of session state provider which contains bug fix related to this issue.…/1.6.1
If your executionTimeout is small then you wouldn’t have run into this issue as it would have been evicted by redis depending on timeout.
You should not set executionTimeout to be very high. It should be in some seconds, But not in hours.
Two questions (after scanning the threads …)
1. Is Redis Session State multi-instance safe? I.e. IF I set my app to 4 instances, am i assures that the cache is shared among them?
2. Where is the final settings API?
thanks –mike
@Siddarth
The StackExchange.Redis Redis client allows for multiple hosts to be listed using the ConnectionMultiplexer, as seen github.com/…/Basics.md. How could I go about setting multiple hosts to pass through to the Redis client? In a previous comment you mentioned opening up the optionsString that can be set, in which case we would be able to pass through multiple hosts.
@Siddharth
@joseph.bi
@XhantiB
@Murat Boduroglu
I've had very good success with the latest build 1.6.1 with the fixed lock release. Performance is like night and day better compared to before with no giant spikes during the day. Looking good!
@Siddharth
Thanks for the update/hotfix release!
@Alec
I will upgrade the solution and give it a try.
I have tried entered the code snippet
[redis-cli]
client = yes
accept = 127.0.0.1:6380
connect = MYSUBDOMAIN.redis.cache.windows.net:6380
Reload the configuration and then ran
redis-cli.exe -p 6380 –a <your access key>
This results in connecting the local server instead of Azure Redis.
So I ran
redis-cli.exe -h MYSUBDOMAIN.redis.cache.windows.net -p 6380 –a <your access key>
But the result is the same as before I set up SSL.
What am I missing?
Figured it out. It looks like localhost, but it really isn't. Took some experimentation and a hint of inspiration to figure it out. 🙂
@Coop99:
1 => You can share same redis cache among any number of instances as Redis is single threaded. All requests will be executed on server one by one in sequence.
2. Where is the final settings API? => Not sure what do you mean by this?
@Dvorac
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("server1:6379,server2:6379");
you can pass this "server1:6379,server2:6379" using "connectionString" settings in session state provider.
I have updated to 1.6.2 in my project, but unfortunately this stills occasionally happens. Siddharth is helping me out on email thread. will see how it goes.
We have released new version of session state provider that allows you to get logs from session state provider and StackExchange.Redis.StrongName.…/1.6.3
Use web.config properties loggingClassName and loggingMethodName for configuring logging. You can find more details in web.config comments when you upgrade to above package. You can basically provide a public, static method which returns a TextWriter. Session state provider and StackExchange.Redis.StrongName both will use this TextWriter object to log details.
Please add a "connectionStringName" attribute to the configuration provider so that the connection string can be centrally located in the connectionStrings section of the config with all the other connection strings.
Hi, we're encountering a nasty deadlock scenario – see stackoverflow.com/…/1170932. Is this the correct place (as well as SO) to report such issues?
This is high priority for us – if I can't find a workaround soon we will have to ditch this provider which would be a shame since for regular browser -> app -> redis requests it works a charm.
Many thanks, Pete
RichardH
"connectionString" parameter already exists.
Peter Kingswell
Can you please provide web.config setting for both app1 and app2? Also provide how does you loging method and class looks like.
I am on version 1.6.3 and I have a problem because in application "X" the Session_Start event in the Global.asax is being hit with every page request. If I set session state mode InProc, I am fine, Session_Start behaves normally, but as soon as I switch to Custom Session State, this problem shows up.
I tried to replicate it in application "Y" and I couldn't recreate the problem. Would you have any ideas where to start from? Most probably its some configuration issue in application X. I tried both local hosting with local RedisCache server and Azure website hosting with Azure Redis Cache server. Same result with both.
@Siddharth, two questions: 1) what is the recommendation for the maxmemory policy when a redis cache is targeted by this session state provider..
Session timeout sliding is still now working.
stackoverflow.com/…/session-timeout-is-not-sliding-in-azure-redis-cache-session-state-provider
I'm using 1.6.3
On request it doesn't slide,it just slides when we touch session.
@Siddharth
Could you please provide a sample code for the logging method? As I am not understanding how I would be using it if doesn't have any parameters. How do I log the errors or something else to my db?
I would like to serialize to Redis as JSON so I can access session data easily from other applications, specifically Node.js services. Have any inroads been made for allowing a custom serializer or in releasing the source?
Hi
i see very often this kind of exception in my production application that use Microsoft.Web.RedisSessionStateProvider version 1.6.0.0
StackExchange.Redis.ConnectionMultiplexer in ExecuteSyncImpl
Timeout performing EVAL, inst: 1, mgr: Inactive, queue: 17, qu=0, qs=17, qc=0, wr=0/0, in=0/0
this is the stack-trace
System.Web.HttpApplication in ExecuteStep at line 21:0
System.Exception ExecuteStep(IExecutionStep, Boolean ByRef)
System.Web.HttpApplication+SyncEventExecutionStep in System.Web.HttpApplication.IExecutionStep.Execute at line 93:0
Void System.Web.HttpApplication.IExecutionStep.Execute()
System.Web.SessionState.SessionStateModule in OnReleaseState at line 477:0
Void OnReleaseState(System.Object, System.EventArgs)
Microsoft.Web.Redis.RedisSessionStateProvider in SetAndReleaseItemExclusive at line 294:0
Void SetAndReleaseItemExclusive(System.Web.HttpContext, System.String, System.Web.SessionState.SessionStateStoreData, System.Object, Boolean)
Microsoft.Web.Redis.RedisConnectionWrapper in Set at line 27:0
Void Set(System.Web.SessionState.ISessionStateItemCollection, Int32)
Microsoft.Web.Redis.StackExchangeClientConnection in Eval at line 233:0
System.Object Eval(System.String, System.String[], System.Object[])
Microsoft.Web.Redis.StackExchangeClientConnection in RetryLogic at line 54:0
System.Object RetryLogic(System.Func`1[System.Object])
Microsoft.Web.Redis.StackExchangeClientConnection in RetryForScriptNotFound at line 39:0
System.Object RetryForScriptNotFound(System.Func`1[System.Object])
Microsoft.Web.Redis.StackExchangeClientConnection+<>c__DisplayClass4 in <Eval>b__3 at line 30:0
System.Object <Eval>b__3()
StackExchange.Redis.RedisDatabase in ScriptEvaluate at line 30:0
StackExchange.Redis.RedisResult ScriptEvaluate(System.String, StackExchange.Redis.RedisKey[], StackExchange.Redis.RedisValue[], StackExchange.Redis.CommandFlags)
StackExchange.Redis.RedisBase in ExecuteSync at line 39:0
T ExecuteSync[T](StackExchange.Redis.Message, StackExchange.Redis.ResultProcessor`1[T], StackExchange.Redis.ServerEndPoint)
StackExchange.Redis.ConnectionMultiplexer in ExecuteSyncImpl at line 586:0
T ExecuteSyncImpl[T](StackExchange.Redis.Message, StackExchange.Redis.ResultProcessor`1[T], StackExchange.Redis.ServerEndPoint)
any idea?
thanks
We have the same problem mentioned by joseph.bi. Any resolution on it?
I have a question, how long a session entry is living in radis? Is it possible to set a time to live? Thanks
@Andrew:
@MaDOnos:
Please send a reproducible test app with which I debug this further to AzureCache@microsoft.com. You can also do the same as session state and output cache provider code is open source now. (github.com/…/aspnet-redis-providers)
@Eric
1) what is the recommendation for the maxmemory policy when a redis cache is targeted by this session state provider. => Depends on your session usage. => Again depends on usage pattern
=> Session is Just way to put and get data from cache. maxmemory policy depends on what you are acrually putting in cache.
@Hugo
check this: stackoverflow.com/…/30948086
@Dan Hounshell: There is no plan for using JSON serializer.
@Alessandro Ursino: check this azure.microsoft.com/…/investigating-timeout-exceptions-in-stackexchange-redis-for-azure-redis-cache
@CultOfSkaro: Enable loggin and share logs with us at AzureCache@microsoft.com. You can also debug it your self using actual session state and output cache code github.com/…/aspnet-redis-providers
@Juan: When session expires it means entry is gone. Session timeout is that time.
Hi there, is there any possibility to find the difference between the NuGet package versions (like CHANGELOG or something)? As of now, our project uses version 1.1.0, which is rather old. Unfortunately, "upgrading and trying" is not a suitable option for us. Any help would be appreciated!
I want it to use it in combination with the StackExchange.Redis.Extensions.Core package which depends on StackExchange.Redis.
Now I get a ambiguous reference exception.
Why does it not depending on StackExchange.Redis?
How is this still in preview? Seeing as Redis is currently strongly recommended by MS for all new cache initiatives…
I'm having problems getting this nuget to work, I've reinstalled the nuget multiple times but still getting the same " Could not load type 'Microsoft.Web.Redis.RedisSessionStateProvider'." error.
Any idea why?
———————————————-Looking for Urgent Help ————————————————-
i have integrated rediss session in my asp.net project with below dll
1)Microsoft.Web.RedisSessionStateProvider.dll version 1.6.5.291
2)StackExchange.Redis.StrongName.dll version 1.0.481.0
for some time it works fine then suddenly it started giving error below
__________________________________________________________________________________________________________________
Error, TagType=InfoTagModule=APPERROR$$$CRITICAL – APPERROR – Application_Error event – ErrorDetails – ** ** Error Report : Error: Timeout performing EVAL, inst: 0, mgr: ExecuteSelect, err: never, queue: 49, qu: 48, qs: 1, qc: 0, wr: 1, wq: 1, in: 0, ar: 0, IOCP: (Busy=0,Free=1000,Min=36,Max=1000), WORKER:(Busy=52,Free=32715,Min=36,Max=32767), clientName: WIN-4QJG4A59IU3
Source: StackExchange.Redis.StrongName Stack Trace: at StackExchange.Redis.ConnectionMultiplexer.ExecuteSyncImpl[T](Message message, ResultProcessor`1 processor, ServerEndPoint server) at StackExchange.Redis.RedisBase.ExecuteSync[T](Message message, ResultProcessor`1 processor, ServerEndPoint server) at StackExchange.Redis.RedisDatabase.ScriptEvaluate(String script, RedisKey[] keys, RedisValue[] values, CommandFlags flags) at Microsoft.Web.Redis.StackExchangeClientConnection.<>c__DisplayClass4.<Eval>b__3() at Microsoft.Web.Redis.StackExchangeClientConnection.RetryForScriptNotFound(Func`1 redisOperation) at Microsoft.Web.Redis.StackExchangeClientConnection.RetryLogic(Func`1 redisOperation) at Microsoft.Web.Redis.StackExchangeClientConnection.Eval(String script, String[] keyArgs, Object[] valueArgs) at Microsoft.Web.Redis.RedisConnectionWrapper.TryUpdateAndReleaseLockIfLockIdMatch(Object lockId, ISessionStateItemCollection data, Int32 sessionTimeout) at Microsoft.Web.Redis.RedisSessionStateProvider) UserSession Items:User Key: 0 Currency Key: 3 Basket Key: 1454212 Date: 11 December 2015 Time:
i m using redis server from AWS
looking for urgent help i m using redis session
I didn't see a response to this question. I want it to use it in combination with the StackExchange.Redis.Extensions.Core package which depends on StackExchange.Redis.
Why do you depend on the strong named StackExchange.Redis.StrongName instead of StackExchange.Redis? At least provide us with a non-strong named package please so we can use other Caching packages that don't have strong named versions.
I am currently working on the Migration of ASP.NET MVC Website to Windows Azure project,So the normal InProc Sessions are not working on Windows Azure so I moved to RedisSessionStateProvider like below.
Session.Add(“fullname”, “Arun”);
Session.Add(“EmailAddress”, “a@b.com”);
Here I am facing an error like ‘Newtonsoft.Json.Linq.JValue’ is not marked as serializable
[SerializationException: Type ‘Newtonsoft.Json.Linq.JValue’ in Assembly ‘Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed’ is not marked as serializable.]
System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) +11488965
System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) +258
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() +161) +182
System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder) +51
System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) +540
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) +131
Microsoft.Web.Redis.RedisUtility.GetBytesFromObject(Object data) in d:\TeamCityBuildAgent\work\f55792526e6d9089\src\Shared\RedisUtility.cs:65
Microsoft.Web.Redis.RedisUtility.GetNewItemsAsList(ChangeTrackingSessionStateItemCollection sessionItems) in d:\TeamCityBuildAgent\work\f55792526e6d9089\src\Shared\RedisUtility.cs:49
Microsoft.Web.Redis.RedisConnectionWrapper.SetPrepare(ISessionStateItemCollection data, Int32 sessionTimeout, String[]& keyArgs, Object[]& valueArgs) in d:\TeamCityBuildAgent\work\f55792526e6d9089\src\RedisSessionStateProvider\RedisConnectionWrapper.cs:113
Microsoft.Web.Redis.RedisConnectionWrapper.Set(ISessionStateItemCollection data, Int32 sessionTimeout) in d:\TeamCityBuildAgent\work\f55792526e6d9089\src\RedisSessionStateProvider\RedisConnectionWrapper.cs:131
Microsoft.Web.Redis.RedisSessionStateProvider.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem) in d:\TeamCityBuildAgent\work\f55792526e6d9089\src\RedisSessionStateProvider\RedisSessionStateProvider.cs:408
System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs) +573
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +141
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
Please let me know where is the problem?
I suggest you post your question to StackOverflow.com – that way you can get more viewers to inspect and submit solutions
Hi Guang Yang
I have a little confusion about Redis Session Storage.
Due to heavy trafic of request on ASP.Net Website Session State become erresponsive. So that I want to replace that with redis.
I just want to know what does “_Write_Lock” means in this situation because I write session one time for each customer when it signed in and use that session until he/she is active (default timeout of session=20) with [SessionState(SessionStateBehavior.ReadOnly)].
Is there is any setting to apply ReadOnly with out locking behavior in this package?
Kindly help me
1484909707.673055 [0 127.0.0.1:63360] “EVALSHA” “e6de9949d13e6886124297b8a995b16a2738524a” “3” “{/_dnwyayg1zxifxbeupti1oqy1}_Write_Lock” “{/_dnwyayg1zxifxbeupti1oqy1}_Data” “{/_dnwyayg1zxifxbeupti1oqy1}_Internal”
1484909707.673103 [0 lua] “GET” “{/_dnwyayg1zxifxbeupti1oqy1}_Write_Lock”
1484909707.673113 [0 lua] “HGETALL” “{/_dnwyayg1zxifxbeupti1oqy1}_Data”
1484909707.673127 [0 lua] “HGET” “{/_dnwyayg1zxifxbeupti1oqy1}_Internal” “SessionTimeout”
1484909707.673138 [0 lua] “EXPIRE” “{/_dnwyayg1zxifxbeupti1oqy1}_Data” “1200”
1484909707.673147 [0 lua] “EXPIRE” “{/_dnwyayg1zxifxbeupti1oqy1}_Internal” “1200”
I’m getting this error on page loads. I think it has something to do with not being able to deserialize objects that were created by a different assembly or version of the assembly.
[SerializationException: The ObjectManager found an invalid number of fixups. This usually indicates a problem in the Formatter.]