问题描述
我在Asp.Net应用程序中使用 System.Timers.Timer
,我需要使用 HttpServerUtility.MapPath
这似乎方法是仅通过 HttpContext.Current.Server.MapPath
。
问题是, HttpContext.Current
是空
在 Timer.Elapsed
事件触发。
I use a System.Timers.Timer
in my Asp.Net application and I need to use the HttpServerUtility.MapPath
method which seems to be only available via HttpContext.Current.Server.MapPath
.The problem is that HttpContext.Current
is null
when the Timer.Elapsed
event fires.
有另一种方式得到一个HttpServerUtility对象的引用?
我可以在我的类的构造函数注入它。是否安全?我怎样才能确保它不会被垃圾在当前请求结束时收集的?
Is there another way to get a reference to a HttpServerUtility object ? I could inject it in my class' constructor. Is it safe ? How can I be sure it won't be Garbage Collected at the end of the current request?
谢谢!
推荐答案
这是可以使用 HostingEnvironment.MapPath()
而不是 HttpContext.Current .Server.MapPath()
我没有在一个线程或定时器事件尝试过,但。
I haven't tried it yet in a thread or timer event though.
一些(非活)解决方案我认为是;
Some (non viable) solutions I considered;
-
我在乎的
HttpServerUtility
的唯一方法是的MapPath
。因此,作为一种替代我可以使用AppDomain.CurrentDomain.BaseDirectory
和建设从此我的路径。 但是,这将如果应用程序使用的虚拟目录失败(矿一样)。
The only method I care about on
HttpServerUtility
isMapPath
. So as an alternative I could useAppDomain.CurrentDomain.BaseDirectory
and build my paths from this. But this will fail if your app uses virtual directories (Mine does).
另一种方法:
加入我需要将在全球
类的所有路径。解决的Application_Start
这些路径。
Another approach: Add all the paths I need to the the Global
class. Resolve these paths in Application_Start
.
这篇关于如何访问的线程或计时器HttpServerUtility.MapPath方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!