1

I am dependent on an HttpContext within a utility class to update cache items but for some reason this always returns a NULL context.

It would seem that an HttpContext cannot be inferred from within a receiver or is there something I might be missing?

override void ItemUpdates(SPItemEventProperties properties)
{
    base.ItemUpdated(properties);
    SPUtilitities.CacheActions(ActionType.Update, properities.ListName);
}

I get a null reference exception within CacheActions(ActionType, string):

void CacheActions(ActionType type, string name)
{
    var context = HttpContext.Current; // null reference exception here
}

2 Answers 2

2

In 2007,

-ed events run asynchronously, so no, you won't have a HttpContext available to you.

-ing events run synchronously, so you might have one.

In addition, because an item can be updated from the API that is not part of a web request, you shouldn't rely on having a HttpContext within an event receiver.

Maybe test for a HttpContext first.

2
  • Hi Paul, so you're saying instead of trying to update the cache in -ed events, I just update them in -ing events?
    – JadedEric
    Mar 15, 2012 at 16:04
  • 1
    Pretty much... but I'd also wrap the call to CacheActions in an if(HttpContext.Current!=null) just incase the item is being updated by something other than a user (eg workflow)
    – Paul Lucas
    Mar 15, 2012 at 23:13
2

What you can do is take a copy of the HttpContext.Current in the contructor for your event handler, and then use it in the event methods themselves:

public class MyHandler : SPItemEventReceiver
{
    System.Web.HttpContext _context = null;
    public MyHandler()
    {
        _context = System.Web.HttpContext.Current;
    }

    public override void ItemUpdated(SPItemEventProperties properties)
   {
        //Use Context Here
   }

It's not pretty, but it does work. I would suggest using with caution.

1
  • Always null in SP2010. Is there anything what I'm doing wrong or have I bad setting? I have SharePoint Foundation 2010 and deploy as Sandboxed solution. Apr 4, 2013 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.