在集成模式下使用HttpContext.Current.Request.ServerVariables [“SERVER_NAME”]会在IIS7中出现错误,如下所示:
http://mvolo.com/blogs/serverside/archive/2007/11/10/Integrated-mode-Request-is-not-available-in-this-context-in-Application_5F00_Start.aspx
我可以在global.asax代码中使用HttpContext.Current.Request.ServerVariables [“SERVER_NAME”]吗?
这与使用类似
- String strPath =
- HttpContext.Current.Server.MapPath(HttpRuntime.AppDomainAppVirtualPath);
代替
- //String strPath =
- HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ServerVariables["PATH_INFO"]);
解决方法
由于在应用程序启动期间管道中没有请求上下文,我无法想象有什么方法可以猜测下一个实际请求可能出现在哪个服务器/端口上.
这是我在经典模式下使用的内容.开销可以忽略不计.
- /// <summary>
- /// Class is called only on the first request
- /// </summary>
- private class AppStart
- {
- static bool _init = false;
- private static Object _lock = new Object();
- /// <summary>
- /// Does nothing after first request
- /// </summary>
- /// <param name="context"></param>
- public static void Start(HttpContext context)
- {
- if (_init)
- {
- return;
- }
- //create class level lock in case multiple sessions start simultaneously
- lock (_lock)
- {
- if (!_init)
- {
- string server = context.Request.ServerVariables["SERVER_NAME"];
- string port = context.Request.ServerVariables["SERVER_PORT"];
- HttpRuntime.Cache.Insert("basePath","http://" + server + ":" + port + "/");
- }
- }
- }
- }
- protected void Session_Start(object sender,EventArgs e)
- {
- //initializes Cache on first request
- AppStart.Start(HttpContext.Current);
- }