Archive

Posts Tagged ‘EventReceiver’

SharePoint: HttpContext.Current is null in event receivers

July 12th, 2013 No comments

    I have never used HttpContext in event receivers till recently, so I was quite surprised when I got a NullReferenceException, trying to access HttpContext.Current.Request within ItemAdding. I would never play with the HttpContext.Current inside such methods as ItemAdded, ItemUpdated and so on as they are usually asynchronous and might be executed on any machine of SharePoint farm. But why the HttpContext.Current is null within synchronous ItemAdding, ItemUpdating, etc. it’s a riddle for me. On the other hand, within the constructor of SPItemEventReceiver the HttpContext.Current is valid. So, the possible workaround here is to get current HttpContext inside the constructor, save it in a variable and then use in synchronous methods. In my opinion the best way in this case is to have a class that is derived from SPItemEventReceiver, manipulates HttpContext and serves as a base class for all custom event receivers. Such simple class could resemble the following:

public class MyAppSPItemEventReceiverBase : SPItemEventReceiver
{
	protected readonly HttpContext _currentContext = null;

	public MyAppSPItemEventReceiverBase()
	{
		_currentContext = HttpContext.Current;
	}
}

Every custom event receiver in that case should look like the following:

public class SomeCustomEventReceiver : MyAppSPItemEventReceiverBase
{
	public override void ItemUpdating(SPItemEventProperties properties)
	{
		base.ItemUpdating(properties);

		properties.AfterProperties["UpdatedFrom"] = GetIpAddress(_currentContext);
	}

	protected static string GetIpAddress(HttpContext context)
	{
		string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
		if (string.IsNullOrEmpty(ipAddress))
			return context.Request.ServerVariables["REMOTE_ADDR"];
		string[] tmpArray = ipAddress.Split(',');
		return tmpArray[0];
	}
}