c# - global.asax中需要UrlHelper

原文 标签 c# asp.net asp.net-mvc asp.net-mvc-3

Need UrlHelper inside global.asax

I need to set up a bunch of paths and URLs when my app starts, ie in global.asax. Using UrlHelper.Content() is the easiest way to do that, but it is not available for use.

So how can I get an instance of it inside global.asax? I tried creating one, but of course RequestContext doesn't exist.

The answer most linked-to is here but that throws exceptions for me. I am using the latest MVC3.

Answer

The code that you have linked to doesn't work for you because you are probably running your application in IIS 7 Integrated Mode (in contrast to Classic Mode). In integrated mode you have no access to the HttpContext in Application_Start. So if on all price you need to generate urls in your Application_Start method forget about UrlHelper, you will need some other method. This being said you could of course use this code in events like Application_BeginRequest, ...

And by the way it's strange that you need to generate urls there. I have never had such need. Maybe you could explain your scenario in more details in order to get a more adapted solution to it.

翻译

我的应用启动时,即在global.asax中,我需要设置一堆路径和URL。使用UrlHelper.Content()是最简单的方法,但是它不可用。

那么如何在global.asax中获取它的实例?我尝试创建一个,但是RequestContext当然不存在。

链接最多的答案是here,但对我来说却抛出异常。我正在使用最新的MVC3。
最佳答案
链接到的代码不适用于您,因为您可能正在IIS 7集成模式下运行应用程序(与经典模式相反)。在集成模式下,您无法访问Application_Start中的HttpContext。因此,如果总的来说您需要在Application_Start方法中生成url,而忘记UrlHelper,则将需要其他方法。话虽如此,您当然可以在Application_BeginRequest等事件中使用此代码...

顺便说一句,您需要在此处生成网址很奇怪。我从来没有这样的需要。也许您可以更详细地解释您的方案,以便获得更适合它的解决方案。
相关推荐

c# - 正则表达式仅在其长度大于值时才匹配模式

c# - 部署工具包建议[关闭]

c# - 在WCF中实例化服务对象的默认行为是什么?

c# - 在C++ / CLI中无法识别命名空间

c# - 硬代码实体框架连接字符串

c# - 谁负责加载数据?

c# - GZIP输出流

c# - 使用XtraTreeList作为下拉演示的PopupContainerEdit

c# - System.Uri.ToString()取消转码为uriencoded的查询字符串。如何停止呢?

c# - 从AJAX服务返回大型JSON文件-WCF