代码之家  ›  专栏  ›  技术社区  ›  VoodooChild

如何获取web应用根目录?

  •  0
  • VoodooChild  · 技术社区  · 14 年前

    我用它来获取应用程序根目录,想知道这是不是一种更新的更好的方法?

    string root = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
    
    1 回复  |  直到 14 年前
        1
  •  3
  •   Ben Griswold    14 年前

    它可能看起来太过火了,但这是我使用的助手例程。我还没有遇到任何麻烦。

    public class UrlHelper
    {
        public static string ApplicationBaseUrl()
        {
            string port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
    
            if (port == null || port == "80" || port == "443")
                port = "";
            else
                port = ":" + port;
    
            string protocol = HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
    
            if (protocol == null || protocol == "0")
                protocol = "http://";
            else
                protocol = "https://";
    
            return protocol + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + port +
                   HttpContext.Current.Request.ApplicationPath;
        }
    }