Omicron Llama

Coding all day, every day.

SharePoint Server Object Model Code in ASP.NET Pages

This article concerns using the SharePoint Server Object model code within ASP.NET pages that are hosted on NON SharePoint web applications.

Granted – for the majority of use-cases you would rather use the SharePoint Managed Client Object Model to perform the majority of your operations – but for the odd occasion where you have a page that does need the server API, this article shows a handy tip.

Let’s say you have some code that runs fine in a Console Application. You run it as a specific user that has access to a SharePoint site and it does what it needs to. You take the same code and execute it from within an ASP.NET webform and it breaks (usually with AccessDeniedException or COMException HRESULT 0x8007005).

The trick here is to set your HttpContext.Current to null for the code that is talking to SharePoint. Like so:

It took us a good few hours to figure this one out. The reason it was failing was because the SPSite constructors actually attempt to use the current HttpContext to load more information about the session’s connection to SharePoint – and set up things like the security context. When the current HttpContext is not null and is not a SharePoint site, things go horribly wrong. In short, the server object model was never intended to be loaded from within an ASP.NET page that isn’t hosted in a SharePoint site.

As a bonus, here is the markup of an ASP.NET page with CodeInPage that you can use to try out things in the server Object Model from the context of a non-SharePoint ASP.NET page. Note the Assembly and Import directives at the top of the page. If you are requiring the Administration namespaces or the Taxonomy assemblies, you’ll have to reference them manually in these directives at the top of the page.

Simply drop this page into a non-SharePoint IIS web site and watch as it talks to SharePoint! Think of this as a Console App in an IIS Web site.

Like I said at the top of the article, for the vast majority of use-cases you’d much rather use the Client Object Model. If you are performing administrative tasks via custom WCF services that are hosted outside of SharePoint, you may encounter similar problems as we had above, so if you need to – unset your HttpContext whilst you talk to SharePoint and set it back once you’re done.



Leave a Reply

Your email address will not be published. Required fields are marked *