Question

I am trying to implement IHttpHandler in SharePoint 2010 and for reference I am using this: http://blogs.msdn.com/b/kaevans/archive/2010/08/04/deploying-an-asp-net-httphandler-to-sharepoint-2010.aspx

But I am getting SPContext.Current is "null" and cannot retrieve the context site.

The url is like:

http://spsvr/sitecoll/subsite/_layouts/myfolder/myhandler.ashx?param1=paramvalue
Was it helpful?

Solution

I am answering my questions.
After reviewing @SimonDoy comment that "That's strange" and realized I am really making some mistake and then realize mistake.

I made mistake, I was running with elevated permission and within that I was referencing SPContext.Current.

The error code

public void ProcessRequest(HttpContext context)
{
    SPSecurity.RunWithElevatedPrivileges(delegate
    {
       // 'SPContext.Current' null reference error
        using (var site = new SPSite(SPContext.Current.Site.ID))
        {
            using (var web = site.OpenWeb(SPContext.Current.Web.ID))
            {
               // codes goes here
            }
        }
    });

}

The fixed code

public void ProcessRequest(HttpContext context)
{
    var curSite = SPContext.Current.Site;
    var curWeb = SPContext.Current.Web;
    SPSecurity.RunWithElevatedPrivileges(delegate
    {
        using (var site = new SPSite(curSite.ID))             {
            using (var web = site.OpenWeb(curWeb.ID))
            {
                // code goes here
            }
        }
    });

}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top