To overcome this problem I created my own WorkerRequest class and a helper method that returns a HttpContext to fake a current http context. Both the class and method take a SPWeb as contructor parameter to put the correct SharePoint context into the http context.
public class FakeSharePointWorkerRequest : SimpleWorkerRequest
{
private readonly string _ServerName;
public FakeSharePointWorkerRequest(SPWeb web) : base(web.ServerRelativeUrl, web.Site.WebApplication.IisSettings[SPUrlZone.Default].Path.FullName, string.Empty, string.Empty, null)
{
_ServerName = web.Site.HostName;
}
public override string GetServerName()
{
return _ServerName;
}
}
public static HttpContext GetFakeHttpContextForSharePoint(SPWeb web)
{
FakeSharePointWorkerRequest workerRequest = new FakeSharePointWorkerRequest(web);
HttpContext httpContext = new HttpContext(workerRequest);
httpContext.Items["HttpHandlerSPWeb"] = web;
httpContext.Items["HttpHandlerSPSite"] = web.Site;
return httpContext;
}
Usage example
using(SPSite site = new SPSite("http://demosite"))
{
using(SPWeb web = site.OpenWeb())
{
bool httpContextIsFake = false;
if (HttpContext.Current == null)
{
// Must be set before using the SPLimitedWebPartManager in a console app
HttpContext.Current = GetFakeHttpContextForSharePoint(web);
httpContextIsFake = true;
}
// Do your own thingies!
// .....
// Don't forget to reset the current http context
if (httpContextIsFake)
{
HttpContext.Current = null;
}
}
}
No comments:
Post a Comment