What to do when SPContext is null but you need it?

Sometimes you stumble upon really strange errors when doing trivial things. When you dig deeper, sometimes it turns out the error comes from the lack of a HttpContext, for example when running some action through STSADM or a timer job.

Recently I faced a strange ArgumentNullException when creating a Content by Query Webpart in C# code. A feature activated event handler was supposed to add a new webpart to a page. Wiring everything up, testing the feature activation through the UI, everything was smooth. As a last step I made the feature hidden and tried to activate the feature through stsadm. And this is where I was left out of luck. STSADM only gave me a very helpful “Value cannot be null”. Digging deeper in the ULS log I caught a callstack which showed that there is some problem getting the SPContext.

To go around this problem, the easiest way is to create a fake SPContext. Waldek and Keith have some great suggestions. The idea is pretty simple:

   1: if (HttpContext.Current == null)
   2: {
   3:   HttpRequest request = new HttpRequest("", web.Url, "");
   4:   HttpContext.Current = new HttpContext(request,
   5:     new HttpResponse(new StringWriter()));
   6:   HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
   7: }
   8: // your code goes here

Be aware that this trick only works when you are working with an SPWeb level object. When dealing with SPList or lower hierarchy items you need to go an other way.

Comments (1)

  1. Peter Holpar says:

    Hi Andras,

    Funny to see I blogged about a very similar solution just a day before your post:


    BTW, the base idea is not mine, it came from one of the comments on my blog: