如何在线程或计时器中访问 HttpServerUtility.MapPath 方法? [英] How to access the HttpServerUtility.MapPath method in a Thread or Timer?

查看:16
本文介绍了如何在线程或计时器中访问 HttpServerUtility.MapPath 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Asp.Net 应用程序中使用了 System.Timers.Timer 并且我需要使用 HttpServerUtility.MapPath 方法,该方法似乎只能通过 HttpContext.Current.Server.MapPath.问题是 HttpContext.CurrentTimer.Elapsed 事件触发时为 null.

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()>

It's possible to use HostingEnvironment.MapPath() instead of 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 is MapPath. So as an alternative I could use AppDomain.CurrentDomain.BaseDirectory and build my paths from this. But this will fail if your app uses virtual directories (Mine does).

另一种方法:将我需要的所有路径添加到 Global 类.在 Application_Start 中解析这些路径.

Another approach: Add all the paths I need to the the Global class. Resolve these paths in Application_Start.

这篇关于如何在线程或计时器中访问 HttpServerUtility.MapPath 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆