2

我想在应用程序启动时只更新一次 web.config。为此,我认为我可以在 Global.asax 中使用 application_start 方法。虽然在向网站发出第一个请求时通常只调用一次 application_start,但当我使用 System.Web.Configuration.WebConfigurationManager 或 Microsoft.Web.Administration.ServerManager 更新 web.config 时,它会为每个 http 请求调用。WebConfigurationManager 的示例代码在这里:

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);

    }

您可以创建一个空的 asp.net Web 应用程序,将此代码添加到 global.asax 并将其托管在 IIS 中。然后刷新页面几次,并在事件日志中查看每次刷新都注册了事件。

当以这种方式更新配置文件时,为什么每次请求都会调用 application_start ?如何在应用程序启动后而不是在每次请求期间更新 web.config 部分?

4

0 回答 0