A common question is how to fake SPContext
in a non-SharePoint context. An answer is found at the bottom of a great post on Structured and repeatable deployment of Content Query Web Part instances, but Google doesn’t seem to find it so hopefully this will help. The whole article is worth a read, but for those looking for a quick answer:
public static SPContext FakeSPContext(SPWeb contextWeb) { // Ensure HttpContext.Current if (HttpContext.Current == null) { HttpRequest request = new HttpRequest("", web.Url, ""); HttpContext.Current = new HttpContext(request, new HttpResponse(TextWriter.Null)); } // SPContext is based on SPControl.GetContextWeb(), which looks here if(HttpContext.Current.Items["HttpHandlerSPWeb"] == null) HttpContext.Current.Items["HttpHandlerSPWeb"] = web; return SPContext.Current; }
I’ve made two slight modifications to Waldek’s original code:
- Since we don’t care about the response, we can use
TextWriter.Null
instead of allocating anew StringWriter()
. - By separating the
HttpContext
andSPContext
logic, we can use this in non-SharePoint web contexts as well as non-web contexts like unit tests and timer jobs.
While this works well for a SPWeb
-based SPContext
, I have not figured out how to fake a list- or item-level SPContext
. It should go without saying that trying to inject a different SPWeb
into an existing SPContext
is a really bad idea. And finally, it is your responsibility to ensure disposal of the SPSite
and SPWeb
you create for the fake context.
Faking SPContext
might be a necessity to work with others’ code (like CQWP), but if you’re needing to use this to work with code you own, consider refactoring to use dependency injection instead.
February 19, 2009 at 6:47 pm
[…] Faking SPContext […]
February 21, 2009 at 1:10 am
[…] Faking SPContext « Solutionizing .NET […]
September 8, 2009 at 2:43 am
[…] faking the current context. I got the concept of faking the SPContext from “Keith Dahlby” blog https://solutionizing.net/2009/02/16/faking-spcontext/ […]
September 3, 2010 at 2:19 pm
[…] what is the answer? Well thanks to the guys over at Solutionizing.net and their article (https://solutionizing.net/2009/02/16/faking-spcontext/) the answer is to just make one up. Worked like a […]
September 21, 2011 at 3:54 pm
[…] https://solutionizing.net/2009/02/16/faking-spcontext/ […]
May 10, 2012 at 9:54 am
Do you think you can also fake the SPContext.Web.CurrentUser?
because it would be a great way to impersonate a user through this part.
May 11, 2012 at 9:45 pm
I expect faking
CurrentUser
would be much more difficult, if it’s possible at all.