Asynchronous Event Receivers and HttpContext


A lesser known trick to make use of the HttpContext in asynchronous Event Receivers in SharePoint 2007 or SharePoint 2010 is to define a constructor on the Event Receiver class that assigns the HttpContext to an internal or private member variable. Next you can access it from the method overrides for handling events.

public class MyER1 : SPItemEventReceiver
{
    // Local reference to HttpContext during Type Construction so we can use it in the Async Methods
    internal HttpContext _ctx = null;

    public MyER1()
    {
        _ctx = HttpContext.Current;
    }

    public override void ItemAdded(SPItemEventProperties properties)
    {
        string requestUrl = _ctx.Request.Url.ToString();
    }
}

There’s a difference in behavior for Lists and Libraries; the former allows you to also read/write from the Context.Session, while the latter doesn’t allow this (Session is null).

I’ve (ab)used this once on a project where I’d call a custom LayoutPage called with QueryString parameters to force a SPListItem.Update(). In the Event Receiver the code would interact with the values of those parameters.

Side note:

Doubt that there’s official support on this. Feel free to drop a comment with your opinion.

 


Links to this post

Comments

Wednesday, 25 Aug 2010 09:23 by Wouter van Vugt
Hi Steven, HttpContext should simply _never_ be used in a event receiver. What if a list item is changed through the timer service? Your code runs, but without HttpContext. What if a console app modifies some data? What if.... Hope it helps, Wouter

Wednesday, 25 Aug 2010 12:00 by Steven Van de Craen
Thanks Wouter, indeed a valid objection to take note of. Was aware of that so a quick fix was to check on that in code. Not a very consistent solution but sometimes SharePoint makes you do unholy things ;)

Wednesday, 25 Aug 2010 02:57 by Wouter
If the app can handle the not running of logic, good stuff! :)

Thursday, 12 Sep 2013 11:34 by Atul
I am using itemAdded EventReceiver and in the constructor public MyER1() { _ctx = HttpContext.Current; } _ctx is coming null. and i want this context to access a file from rootfolder from server

Thursday, 12 Sep 2013 11:57 by Steven Van de Craen
Hi Atul, Have you set ItemAtted to be Synchronous ? Which SP version are you referring to?

CAPTCHA Image Validation