13 June 2012

SharePoint - Access the object model from a custom web service

I ran into a serious issue yesterday. I had built a custom web service to access a list on our SharePoint site, and everything seemed to work fine. But when I was not logged in, the site kept asking for my credentials and the line where I accessed the list threw a 401 - unauthorized. I tried to get to the list using SPContext, but even with RunWithElevatedPrivileges around it, it wouldn't work. The only thing I could do with SPContext however was get the GUID of the site and web that contained my list. So I got both of these and used them to gain access to my list like this:
SPSecurity.RunWithElevatedPrivileges(delegate() {
  using (SPSite spSite = new SPSite(new Guid("846ca17c-b8eb-4b04-8888-f5b7a1c6cfa3"))) {
    using (SPWeb web = spSite.OpenWeb(new Guid("14ba40e8-ee72-40fe-8b98-d1b1f72355aa"))) {
      list = web.Lists["Kalender"];
    }
  }
});
And surprise: this works!

No comments:

Post a Comment