Search code examples
c#asp.netiisiis-10

How do you set the Session State - Cookie Settings - Timeout in an IIS web application using Microsoft.Web.Administration?


I am using Microsoft.Web.Administration to create IIS web applications under a selected parent site programmatically. I can create the application just fine with the code below but I'm not sure what to do to change this specific aspect of the application (the cookie timeout value) through the Application variable.

Microsoft.Web.Administration.Application new_parent_app = target_trial_site.Applications.Add("/Test", new_app_path);
new_parent_app.ApplicationPoolName = "DefaultAppPool";
new_parent_app.SetAttributeValue("system.web/sessionState/timeout", 720); // what should go here? or is it a different function like SetMetadata?

Here is a picture of the value I'm trying to change in the IIS UI, for reference: cookie settings timeout textbox

Microsoft's developer site here is not clear on how I would do this either.

Thanks in advance for any help.


Solution

  • You must go through the server/app/section/setting hierarchy,

    using System;
    using Microsoft.Web.Administration;
    
    namespace CookieTimeout
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Get the server manager
                ServerManager serverManager = new ServerManager();
    
                // Get the app configuration
                Configuration config = serverManager.Sites["Default Web Site"].Applications["/App"].GetWebConfiguration();
    
                // Get the session state section
                ConfigurationSection sessionStateSection = config.GetSection("system.web/sessionState");
    
                // Set the cookie timeout to 20 minutes
                sessionStateSection["timeout"] = TimeSpan.FromMinutes(20);
    
                // Save the changes
                serverManager.CommitChanges();
    
                // Display a message
                Console.WriteLine("Cookie timeout set to 20 minutes);
            }
        }
    }