Skip to content

Moving the sessionState connection string to a separate config file

Typically, the sessionState for SQL is specified in the web.config something like this:

<sessionState mode="SQLServer"
    sqlConnectionString="Data Source=dbserver;User Id=username;Password=password"
    cookieless="false" timeout="20"/>

However, to make switching connection strings between development, QA, and live environments easier in our build process, we store all of our connection strings in a separate config file which is referenced in the web.config in this way:

<connectionStrings configSource="DevConnections.config"/>

Our build process automatically swaps out the configSource value based on the target environment. It was only logical to want to move the sessionState settings to a separate config file as well.  The build process could make a very similar step to modify the sessionState for the target environment.  So, are web.config now contains this line:

<sessionState configSource="LiveSessionState.config" />

and LiveSessionState.config contains:

<sessionState mode="SQLServer"
    sqlConnectionString="Data Source=dbserver;User Id=username;Password=password"
    cookieless="false" timeout="20"/>

At this point, our live application throws an exception because the sessionState connection string does not specify an Initial Catalog.  To be honest, this is first time I’ve noticed this connection string doesn’t give the Initial Catalog like all of our other connection strings.  This is because sessionState assumes the database name is ASPState.  By moving the settings to a separate config file, we have to specify the database name?  Well, OK.  So, we add it and we get a new exception because we specifed the Initial Catalog.  Frustration begins to set in since we only use a SQL session state server in our live environment.

Digging deeper, there is an additional parameter, allowCustomSqlDatabase, for sessionState that allows us to specify the Initial Catalog in case we didn’t want to use ASPState and we added it:

<sessionState mode="SQLServer" allowCustomSqlDatabase="true"
    sqlConnectionString="Data Source=dbserver;Initial Catalog=ASPState;User Id=username;Password=password"
    cookieless="false" timeout="20"/>

This feels a little quirky, but the problem is solved.

Published inUncategorized