IIS Recycle Global.asax

后端 未结 4 1666
误落风尘
误落风尘 2020-12-06 12:45

Is it possible to catch an recycle event in the global.asax?

I know Application_End will be triggered but is there a way to know that it was triggered by a recycle o

4条回答
  •  攒了一身酷
    2020-12-06 13:20

    I found this article on Scott Guthries's blog:

    Logging ASP.NET Application Shutdown Events

    Someone on a listserv recently asked whether there was a way to figure out why and when ASP.NET restarts application domains. Specifically, he was looking for the exact cause of what was triggering them on his application in a production shared hosted environment (was it a web.config file change, a global.asax change, an app_code directory change, a directory delete change, max-num-compilations reached quota, \bin directory change, etc).

    Thomas on my team has a cool code-snippet that he wrote that uses some nifty private reflection tricks to capture and log this information. It is pretty easy to re-use and add into any application, and can be used to log the information anywhere you want (the below code use the NT Event Log to save it – but you could just as easily send it to a database or via an email to an admin). The code works with both ASP.NET V1.1 and ASP.NET V2.0.

    Simply add the System.Reflection and System.Diagnostics namespaces to your Global.asax class/file, and then add the Application_End event with this code:

    public void Application_End() {
    
        HttpRuntime runtime = 
           (HttpRuntime) typeof(System.Web.HttpRuntime).InvokeMember("_theRuntime",
              BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, 
              null, null, null);
    
        if (runtime == null)
            return;
    
        string shutDownMessage = 
           (string) runtime.GetType().InvokeMember("_shutDownMessage",
               BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,
               null, runtime, null);
    
        string shutDownStack = 
           (string) runtime.GetType().InvokeMember("_shutDownStack",
               BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,
               null, runtime, null);
    
        if (!EventLog.SourceExists(".NET Runtime")) {
            EventLog.CreateEventSource(".NET Runtime", "Application");
        }
    
        EventLog log = new EventLog();
        log.Source = ".NET Runtime";
    
        log.WriteEntry(String.Format(
              "\r\n\r\n_shutDownMessage={0}\r\n\r\n_shutDownStack={1}", 
              shutDownMessage, shutDownStack),
           EventLogEntryType.Error);
    }
    

提交回复
热议问题