zoukankan      html  css  js  c++  java
  • 曲线救国: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;
            }

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

  • 相关阅读:
    <JZOJ5912>VanUSee
    <JZOJ5910>duliu
    <JZOJ5913>林下风气
    pytest学习笔记(二)
    试用saucelabs进行浏览器兼容性测试
    pytest学习笔记(一)
    SSM框架搭建,以及mybatis学习
    游戏2048的python实现
    使用svn在github上下载文件夹
    jenkins集成python的单元测试
  • 原文地址:https://www.cnblogs.com/Gyoung/p/4404542.html
Copyright © 2011-2022 走看看