SPContext.Current.Site = NullReferenceException for asp.net page in sharepoint

To run asp.net application in the SharePoint context, it should be copied into the C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS directory. If it belongs to different box then SPContext.Current.Site will not work. If ASP.net page is opened from SharePoint context then try following:

SPSite objSite = new SPSite(SPContext.Current.Site.ID);

If it doesn’t work then you need to create SPSite object using url

SPSite objSite = new SPSite ("http://sharepointsite");

But this is hardcoded. If you want to make it generalize and the page belongs to sharepoint context then do following:

SPSecurity.RunWithElevatedPrivileges(delegate { StartJob(); });
void StartJob()
{
string pageUrl = Request.Url.GetLeftPart(UriPartial.Authority);
SPSite objSite = new SPSite(pageUrl);

}


This will take Site url from the page url and create SPSite object. There is no change required to deploy on another MOSS server.

No comments:

Post a Comment