Using MySql as ASP.NET Session Store Provider

MySQL Connector/Net from version 6.1 has included a custom Session State Provider. This provider enables you to store session state in a MySQL database and is useful if you are running your site on a web farm and you don't want to use the build in MSSQL.

There is an article in the MySql documentation on how to get started, I did find that of course, it wouldn't work correctly in Medium Trust. So I downloaded the source for the 6.6.5 version and started debugging. I had read there were some bugs in the earlier versions causing the session to lock.

The first thing that needs to change is how the web.configuration file is accessed, in Medium Trust you will get a security error.

// Get configuration element.
Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath);
sessionStateConfig = (SessionStateSection)webConfig.SectionGroups["system.web"].Sections["sessionState"];

To the following as the OpenWebConfiguration method  throws an exception, System.Security.Permissions.FileIOPermission, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089

// Get configuration element.
sessionStateConfig = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");

I compiled my own version, if you have a Full Trust environment you could probably go with the original version.

You also need to configure the web.config file to uses the new provider.

        <remove name="LocalMySqlServer"/>
        <add name="LocalMySqlServer" connectionString="Server=;Database=aspnet_state;password=mypassword;User ID=myuser"/>
<sessionState cookieless="false" regenerateExpiredSessionId="true" mode="Custom" customProvider="MySqlSessionStateStore">
                <add name="MySqlSessionStateStore" type="MySql.Web.SessionState.MySqlSessionStateStore, MySql.Web" connectionStringName="LocalMySqlServer" writeExceptionsToEventLog="false" autogenerateschema="True" />