Application start called each time page is refreshed when config is changed in application_start

1k views Asked by At

I want to update web.config just once when application is started. For this I thought I can use application_start method in Global.asax. While application_start is called only once normally when the first request is made to website, it is being called for each http request when I use either System.Web.Configuration.WebConfigurationManager or Microsoft.Web.Administration.ServerManager to update web.config. Example code with WebConfigurationManager is here:

protected void Application_Start(object sender, EventArgs e)
    {
        Configuration config =WebConfigurationManager.OpenWebConfiguration(null);
        config.AppSettings.Settings.Remove("MyVariable");
        config.AppSettings.Settings.Add("MyVariable", "MyValue");
        config.Save(); 

        // Add event to event log to monitor when this method is called
        string sSource= "TryApplicationStart";
        string sLog= "Application";
        string sEvent= "Sample Event"; 

        if (!EventLog.SourceExists(sSource))
            EventLog.CreateEventSource(sSource, sLog);
        EventLog.WriteEntry(sSource, sEvent);
        EventLog.WriteEntry(sSource, sEvent,
            EventLogEntryType.Warning, 234);

    }

You can create an empty asp.net web application, add this code to global.asax and host it in IIS. Then refresh the page a couple of times and see in event log that there are events registered for each refresh.

Why is application_start being called for each request when config file is updated in this way? How can I update web.config sections once the application is started and not during each request?

0

There are 0 answers