如何解析 ASP.NET“~”没有控件的情况下应用程序到网站根目录的路径?
我想从非页面上下文(例如 Global.asax (HttpApplication)、HttpModule、HttpHandler 等)内部解析“~/whatever”,但只能找到特定于控件(和页面)的此类解析方法。
我认为应用程序应该有足够的知识来能够在页面上下文之外映射它。不?或者至少对我来说是有意义的,在其他情况下,只要知道应用程序根,它就应该可以解决。
更新:原因是我在 web.configuration 文件中粘贴了“~”路径,并希望从上述非控制场景中解决它们。
更新 2: 我试图将它们解析为网站根目录,例如 Control.Resolve(..) URL 行为,而不是文件系统路径。
I want to Resolve "~/whatever" from inside non-Page contexts such as Global.asax (HttpApplication), HttpModule, HttpHandler, etc. but can only find such Resolution methods specific to Controls (and Page).
I think the app should have enough knowledge to be able to map this outside the Page context. No? Or at least it makes sense to me it should be resolvable in other circumstances, wherever the app root is known.
Update: The reason being I'm sticking "~" paths in the web.configuration files, and want to resolve them from the aforementioned non-Control scenarios.
Update 2: I'm trying to resolve them to the website root such as Control.Resolve(..) URL behaviour, not to a file system path.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
答案如下:
ASP.Net:使用系统共享/静态函数中的.Web.UI.Control.ResolveUrl()
Here's the answer:
ASP.Net: Using System.Web.UI.Control.ResolveUrl() in a shared/static function
您可以通过直接访问
HttpContext.Current
对象来做到这一点:需要注意的一点是,
HttpContext.Current
只会是非null
code> 在实际请求的上下文中。例如,它在Application_Stop
事件中不可用。You can do it by accessing the
HttpContext.Current
object directly:One point to note is that,
HttpContext.Current
is only going to be non-null
in the context of an actual request. It's not available in theApplication_Stop
event, for example.在 Global.asax 中添加以下内容:
In Global.asax add the following:
我还没有调试这个傻瓜,但我把它作为手动解决方案扔在那里,因为在 Control 之外的 .NET Framework 中找不到 Resolve 方法。
这对我来说确实适用于“~/whatever”。
I haven't debugged this sucker but am throwing it our there as a manual solution for lack of finding a Resolve method in the .NET Framework outside of Control.
This did work on a "~/whatever" for me.
不要使用 MapPath,而是尝试使用 System.AppDomain.BaseDirectory。对于网站来说,这应该是您网站的根目录。然后执行 System.IO.Path.Combine 与您要传递给 MapPath 的任何内容(不带“~”)。
Instead of using MapPath, try using System.AppDomain.BaseDirectory. For a website, this should be the root of your website. Then do a System.IO.Path.Combine with whatever you were going to pass to MapPath without the "~".