曲线救国:IIS7集成模式下如何获取网站的URL

如果我们在Global中的Application_Start事件中访问HttpContext.Current.Request对象,如:

        protected void Application_Start()
        {
            var url=HttpContext.Current.Request.Url.ToString();
        }

只是简单的想取一下当前网站的URL。在调试的时候一切正常,但当我们把网站发布到IIS上面的时候,如果IIS应该程序池在集成模式,就会是会报“请求在此上下文中不可用”的异常,但如果是经典模式就不会。dudu这篇文章有详细的说明 http://www.cnblogs.com/dudu/archive/2011/10/14/Application_Start_Context_Request.html

一般来说,解决这个问题,两个方法:

1.将IIS应用程序池改成经典模式

2.不要在Application_Start中访问HttpContext.Current.Request对象。

但是在有些特殊情况下,在集成模式下能不能在Application_Start获取当前站点的URL。

虽然我们不能调用HttpContext.Current.Request对象,但是我们通过System.Web.Hosting.HostingEnvironment.ApplicationID可以获取IIS站点的部署信息。

通过站点的绑定信息间接获取网站的URL.

     void Application_Start(object sender, EventArgs e)
        {
            //var url = HttpContext.Current.Request.Url.ToString();
            var url = GetUrl();
            // 在应用程序启动时运行的代码
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterOpenAuth();
        }

        private string GetUrl()
        {
            string path = System.Web.Hosting.HostingEnvironment.ApplicationID; //值类似于:/LM/W3SVC/3/ROOT
            string url = string.Empty;
            try
            {
                //如果HttpContext可以访问就直接返回通过HttpContext获取的结果
                return HttpContext.Current.Request.Url.ToString();
            }
            catch (Exception)
            {
            }
            // 将Path转换成IIS路径
            path = path.Replace("/LM", "").Replace("/ROOT", "");
            string entPath = string.Format("IIS://localhost{0}", path);
            DirectoryEntry entry = new DirectoryEntry(entPath);
            if (entry.Properties.Contains("ServerBindings"))
            {
                var bingdings = entry.Properties["ServerBindings"].Value.ToString();//得到的结果类似于10.188.188.13:8082: 
                //去掉结尾的 : 号
                if (bingdings.EndsWith(":"))
                {
                    bingdings = bingdings.Substring(0, bingdings.Length - 1);
                }
                url = "http://"+bingdings;
            }

            return url;
        }

 当然这种方法只适用于我们只需要知道网站域名的情况下,或我们可以确定第一次访问网站的初始页面。

posted @ 2015-04-09 09:04  Gyoung  阅读(1885)  评论(3编辑  收藏  举报