Pergunta

I wish to change the session state provider dynamically when a web page loads.

Locally, while developing, we use the following:

<sessionState mode="InProc" />

But production code runs like this:

<sessionState mode="Custom" customProvider="CustomSessionStateProvider">
  <providers>
    <add name="CustomSessionStateProvider" type="Library.CustomSessionStateProvider" applicationName="AppName" />
  </providers>
</sessionState>

Is it not possible to change which provider the sessionState uses at runtime before a page loads? It would be determined by some kind of configurable item:

if(Environmental.IsProduction)
{
    // Use custom provider
}
else
{
    // Use InProc
}

We do use different config files per environment, but this feature needs to be available in all environments.

Foi útil?

Solução

You can use Web Config Transformations to achieve this.

This will allow you to specify transform sections in your web.config and have seperate files for different environments that replace the transform tokens during build.

More info here: http://msdn.microsoft.com/en-us/library/dd465318%28v=vs.100%29.aspx

When you deploy a Web site, you often want some settings in the deployed application's Web.config file to be different from the development Web.config file. For example, you might want to disable debug options and change connection strings so that they point to different databases. This topic explains how to set up a Web.config transform file that is applied automatically during deployment in order to make changes to the deployed versions of Web.config files.

Web.config transforms are part of a broader group of settings that you can configure to automate the deployment process. For information about the tasks that are involved in setting up automated deployment, see the following topics:

Outras dicas

You can achieve this using Reflection:

protected void Application_Start() {
    var privateFieldFlags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;

    //Get session state section
    var sessionStateSection = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
    var values = typeof(ConfigurationElement).GetField("_values", privateFieldFlags).GetValue(sessionStateSection);
    var entriesArray = values.GetType().BaseType.GetField("_entriesArray", privateFieldFlags).GetValue(values);

    //Get "Mode" entry (index: 2)
    var modeEntry = (entriesArray as System.Collections.ArrayList)[2];
    var entryValue = modeEntry.GetType().GetField("Value", privateFieldFlags).GetValue(modeEntry);

    //Change entry value to InProc
    entryValue.GetType()
            .GetField("Value", privateFieldFlags)
            .SetValue(entryValue, System.Web.SessionState.SessionStateMode.InProc);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top