C#获取应用程序Uri

/// 
        /// Get application url
        /// 
        private String GetCurApplicationUrl()
        {
            String url = HttpContext.Current.Request.Url.IsDefaultPort
                ? HttpContext.Current.Request.Url.Host
                : string.Format("{0}:{1}", HttpContext.Current.Request.Url.Host, HttpContext.Current.Request.Url.Port.ToString());
            if (HttpContext.Current.Request.ApplicationPath != "/")///IT.CCGFrontEnd2
                return "http://" + url + HttpContext.Current.Request.ApplicationPath;
            else return "http://" + url;
        }

此方法固定了http如果是https则不灵活,所以使用下边的属性

/// 
        /// Gets the absolute root
        /// 
        private Uri AbsoluteWebRoot
        {
            get
            {
                var context = HttpContext.Current;
                UriBuilder uri = new UriBuilder();//http://localhost/IT.CCGFrontEnd2/
                uri.Host = context.Request.Url.Host;//localhost
                if (!context.Request.Url.IsDefaultPort)
                {
                    uri.Port = context.Request.Url.Port;
                }

                uri.Path = VirtualPathUtility.ToAbsolute("~/");///IT.CCGFrontEnd2/

                Uri absoluteWebRoot = uri.Uri;

                return absoluteWebRoot;
            }
        }

测试

//http://localhost/IT.CCGFrontEnd2/BPC/Dingding/Report.aspx?qid=261 
    var preUri = GetCurApplicationUrl.AbsoluteUri;//http://localhost/IT.CCGFrontEnd2/
        var preUri = GetCurApplicationUrl.AbsolutePath;///IT.CCGFrontEnd2/

 

你可能感兴趣的:(C#获取应用程序Uri)