by

How to create your own SharePoint HttpContext

Quick and short. Here's a function that I use to create my own SharePoint HttpContext objects outside the SharePoint websites domain. I hope it is somehow useful to someone out there as well.

    1         /// <summary>
    2         /// Enables a share point call from anywhere by creating your own context.
    3         /// </summary>
    4         /// <param name="siteCollectionUrl">The site collection URL where you want to create the context.</param>
    5         /// <example>
    6         /// EnableSharePointCallByCreatingYourOwnContext("http://mysite.com.au");
    7         /// </example>
    8         private void EnableSharePointCallByCreatingYourOwnContext(string siteCollectionUrl)
    9         {
   10             using (var site = new SPSite(siteCollectionUrl))
   11             {
   12                 using (var web = site.OpenWeb())
   13                 {
   14                     // assumes that context does not exists
   15                     var contextCreated = false;
   16 
   17                     // if it does not exists, then create it
   18                     if (HttpContext.Current == null)
   19                     {
   20                         contextCreated = true;
   21                         // creates a request object for the current web URL
   22                         var request = new HttpRequest(string.Empty, web.Url, string.Empty);
   23 
   24                         // open the pipe to output the http stream
   25                         HttpResponse httpResponse;
   26                         using (var responseWriter = new StringWriter())
   27                         {
   28                             httpResponse = new HttpResponse(responseWriter);
   29                         }
   30 
   31                         // creates the context
   32                         HttpContext.Current = new HttpContext(request, httpResponse);
   33 
   34                         // HttpHandlerSPWeb is a the property name where you must assign the current web
   35                         // in order to associate the newly created context to sharepoint
   36                         if (HttpContext.Current.Items != null)
   37                         {
   38                             HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
   39                         }
   40                     }
   41 
   42                     // ...
   43                     // do whatever you want to do here
   44                     // ...
   45 
   46                     // return the application context to the original state prior the execution
   47                     if (contextCreated)
   48                     {
   49                         HttpContext.Current = null;
   50                     }
   51                 }
   52             }
   53         }

See you later

By