Skip to content

SPContext and/or Session is null in HttpModule

May 11, 2011

When developing a custom HttpModele we run into the following problems:

Problem: SPContext is null
Solution: SPContext is not available in BeginRequest eventhandler yet. Try moving your code to the PreRequestHandlerExecute where SPContext is available.

Problem: HttpContext.Current.Session is null in PreRequestHandlerExecute, too.
Solution: HttpContext.Current.Session is only available when the module call was triggered by an aspx page. The module also gets called for jpg, css requests. In these cases the session is null.

    public class MyModule : IHttpModule
        public void Init(HttpApplication application)
            application.BeginRequest += new EventHandler(application_BeginRequest);
            application.PreRequestHandlerExecute += new EventHandler(application_PreRequestHandlerExecute);

        void application_BeginRequest(object sender, EventArgs e)
            //SPContext is NOT YET available here

        void application_PreRequestHandlerExecute(object sender, EventArgs e)
            //SPContext is available here

            if (HttpContext.Current.Request.Path.IndexOf(".aspx") > 0)
                // HttpContext.Current.Session is available here
                // HttpContext.Current.Session is null here


From → .NET, WSS 3.0

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: