Using the SPContext in HttpModules in SharePoint

By Geert van der Cruijsen at May 23, 2010 17:20
Filed Under: Asp.net, SharePoint

When you are building custom HttpModules in SharePoint a common thing to do is to use the SPContext object to get acces to your SPSite, SPWeb, SPList or SPListItem. When doing this you have to be careful because the SPContext isn’t available everywhere because HttpModules can run early in the ASP.Net request pipeline so the SPContext object isn't available yet.

if you try to acces the SPContext to early in the pipeline you’ll get a System.InvalidOperationException error.

The earliest you can use the SPContext is in the “PreRequestHandlerExecute” so don’t use it at the BeginRequest event what most people try to use when they want to add code as early in the pipeline as possible

code:

   1: public class RequestHandlingHttpModule : IHttpModule, IRequiresSessionState
   2: {
   3:  
   4:     public void Dispose() {}
   5:  
   6:     public void Init(HttpApplication application)
   7:     {
   8:         application.BeginRequest += application_BeginRequest;
   9:         application.PreRequestHandlerExecute += new EventHandler(application_PreRequestHandlerExecute);
  10:     }
  11:  
  12:     void application_PreRequestHandlerExecute(object sender, EventArgs e)
  13:     {
  14:         string webUrl = SPContext.Current.Web.Url;
  15:     }
  16:  
  17:     void application_BeginRequest(object sender, EventArgs e)
  18:     {
  19:         // do not use SPContext here it will throw a System.InvalidOperationException 
  20:         // this event is fired before PreRequestHandlerExecute so code that doesn't uses SPContext goes here
  21:     }
  22:  
  23: }

Geert van der Cruijsen

Add comment



biuquote
Loading