I have CUSTOM WCF Service hosted in IIS as a part of SharePoint Virual Directory (ISAPI under _vti_bin). This Web Service is triggered by Custom Pages and Controls on the same FARM Server. This service does nothing but adds a Web Part of user’s choice to a Page. For this I have used SharePoint Object Model. now the actual problem, When I try to user //SPSite oSite = SPContext.Current.Site in my code, I was getting following error “Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack”.
After doing some analysis I found that it is actually a “Access Denied” error which is thrown while trying to create SPSite object.
Resolution: Use SPSecurity.RunWithElevatedPrivileges, if you using Object Model in your Service Layer.
SPSite oSite = SPContext.Current.Site;
Guid siteGuid = oSite.ID;
//Get the SPSite Object
// I am using SPContext within RunWithElevatedPrivileges
//Opening the Site with new SPSite(siteGuid);
oSite = new SPSite(siteGuid);
//Open the Web now
oWebSite = oSite.OpenWeb();