Accessing QueryString parameters in "After" events like ItemAdded, ItemDeleted

Unlike “Before” event (e.g. ItemAdding, ItemDeleting) “After” events (e.g. ItemAdded, ItemDeleted) in SharePoint usually fire asynchronously on a different thread then the http request.

That means that the HttpContext and HttpRequest objects cannot be retrieved in these events as they do not exist on the current stack.

That means that there is no way to directly retrieve querystring parameters or other values like http headers inside these “After” events.

A simple workaround for this problem is to retrieve the relevant information inside the “before” event and pass it to the “after” event using the HttpRuntime cache:

public override void ItemAdding(SPItemEventProperties eventProperties)
{
    // retrieve QueryString parameter
    string queryString = HttpContext.Current.Request.QueryString[…];
                
    // Get ListItem the event fired on
    SPListItem currentItem = eventProperties.ListItem;
                
    // copy query string parameter value to the cache using the unique id of the item   
    // as cache key

    HttpRuntime.Cache[currentItem.UniqueId] = queryString;
}

public override void ItemAdded(SPItemEventProperties eventProperties)
{
   // Get ListItem the event fired on
   SPListItem currentItem = eventProperties.ListItem;
                
   // copy query string parameter value from using the unique id of the item as
   // cache key

   string queryString = HttpRuntime.Cache[currentItem.UniqueId] as string;
                
   // remove item from cache to free up space
   HttpRuntime.Cache.Remove(currentItem.UniqueId);

   …
}

 

2 Comments


  1. Does not work under Sandbox. HttpContext.Current is null in sandbox event receivers.

    Reply

  2. It Really Works!! Thanks for the post! 🙂

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.