asp.net – 在集成模式下替换HttpContext.Current.Request.ServerVariables [“SERVER_NAME”]

前端之家收集整理的这篇文章主要介绍了asp.net – 在集成模式下替换HttpContext.Current.Request.ServerVariables [“SERVER_NAME”]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在集成模式下使用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”]吗?

这与使用类似

  1. String strPath =
  2. HttpContext.Current.Server.MapPath(HttpRuntime.AppDomainAppVirtualPath);

代替

  1. //String strPath =
  2. HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ServerVariables["PATH_INFO"]);

解决方法

由于在应用程序启动期间管道中没有请求上下文,我无法想象有什么方法可以猜测下一个实际请求可能出现在哪个服务器/端口上.

这是我在经典模式下使用的内容.开销可以忽略不计.

  1. /// <summary>
  2. /// Class is called only on the first request
  3. /// </summary>
  4. private class AppStart
  5. {
  6. static bool _init = false;
  7. private static Object _lock = new Object();
  8.  
  9. /// <summary>
  10. /// Does nothing after first request
  11. /// </summary>
  12. /// <param name="context"></param>
  13. public static void Start(HttpContext context)
  14. {
  15. if (_init)
  16. {
  17. return;
  18. }
  19. //create class level lock in case multiple sessions start simultaneously
  20. lock (_lock)
  21. {
  22. if (!_init)
  23. {
  24. string server = context.Request.ServerVariables["SERVER_NAME"];
  25. string port = context.Request.ServerVariables["SERVER_PORT"];
  26. HttpRuntime.Cache.Insert("basePath","http://" + server + ":" + port + "/");
  27. }
  28. }
  29. }
  30. }
  31.  
  32. protected void Session_Start(object sender,EventArgs e)
  33. {
  34. //initializes Cache on first request
  35. AppStart.Start(HttpContext.Current);
  36. }

猜你在找的asp.Net相关文章