Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to fool HTTPContext.Current?

Tags:

c#

I have this line of code in an assembly:

 HttpContext.Current.Server.MapPath

This works great if the assembly is being used in a web service.

but if I take it out of the web service its obivously not going to work, because HTTPContext does not exist.

Is it at all possible to fool httpContext into thinking it exists, really just to get the relative path structure of a directory?

I mean somehow manually creating the HTTPContext object, and assigning it a base directory?

Update

Is there a more generic approach to : HttpContext.Current.Server.MapPath

Something that can work in executables, and something that can work in web?

like image 583
JL. Avatar asked Dec 13 '22 03:12

JL.


2 Answers

HttpContext.Current "gets or sets the HttpContext object". And HttpContext has a public constructor which takes a HttpWorkerRequest (abstract, use SimpleWorkerRequest) and you would be able to fake the HttpContext completely.

I agree with others that you could refactor your code to remove this dependency, but there are scenarios when you must fake the HttpContext.Current stuff, in which case this question will show up if you search...

like image 60
sisve Avatar answered Dec 16 '22 17:12

sisve


It sounds to me like you need to wrap up the call to HttpContext inside another object which you can then switch out using IOC for the correct object in the correct environment. E.g. something like IMapPath as your interface and then your implementation could be HttpMapPath or ConsoleAppMapPath etc.

like image 20
Michael Ciba Avatar answered Dec 16 '22 17:12

Michael Ciba