代码改变世界

IIS 7.0集成模式中Application_Start不能使用HttpContext.Current

2009-09-21 22:57  Tam  阅读(1106)  评论(0编辑  收藏  举报

在IIS7集成模式中,当我们在Global.asax的Application_Start中使用HttpContext.Current.Request.ApplicationPath获得当前虚拟目录路径,会得到以下的错误:

Server Error in '/IIS' Application.

Request is not available in this context

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Request is not available in this context

Source Error:

Line 6: { Line 7: // Code that runs on application startup Line 8: var appPath = HttpContext.Current.Request.ApplicationPath; Line 9: } Line 10: 

根据ASP.NET 2.0 Breaking Changes on IIS 7.0中的第十六条,我们可以清楚看到Application_Start事件中已不能使用HttpContext.Current。

如果我们只是需要获取当前的虚拟目录名,可以使用HttpRuntime.AppDomainAppVirtualPath代替。