Sunday, March 27, 2011

Using HttpModule instead of Global.asax

How do I convert:

<%@ Application Language="C#" %>

<script runat="server">

    void Session_Start(object sender, EventArgs e) 
    {


    }

</script>

To a scheme that uses HttpModule?

Also, can I write the Global.asax as pure C# instead of using tags?

From stackoverflow
  • In the init of your custom module you need to retrieve the Session-module and add an event handler for the Start event.

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(Begin_Request);
        IHttpModule sessionModule = context.Modules["Session"];
        if(sessionModule != null && 
            sessionModule.GetType() == typeof(System.Web.SessionState.SessionStateModule))
        {
            (sessionModule as System.Web.SessionState.SessionStateModule).Start 
              += new EventHandler(CustomHttpModule_Start);
        }
    }
    

    Also, can I write the Global.asax aspure C# instead of using tags?

    Yes you can add a code behind in the in the Global.asax and change the content to

    <%@ Application Language="C#" CodeBehind="Global.asax.cs" Inherits="Global" %>
    

    Your code behind should inherit from System.Web.HttpApplication

    public class Global : System.Web.HttpApplication
    {
      public Global()   { }
    
      void Session_Start(object sender, EventArgs e)
      {
          // Code that runs when a new session is started
      }
    }
    

0 comments:

Post a Comment