/// <summary> /// 将当前相对于服务器根目录的相对Url(如“/Upload/File”)转换为绝对Url网址,如:“http://localhost:6068/Upload/File” /// </summary> public static string ToAbsoluteUrl(this 通用扩展.PathString o) { if (o.Value.ToLower().StartsWith("http://")) { return(o.Value); } return("http://" + WebSite变量.Current.Request.ServerVariables["SERVER_NAME"] + ":" + WebSite变量.Current.Request.ServerVariables["Server_Port"] + o); }
/// <summary> /// 将指向当前Web站点下的绝对路径转换为相对于当前页的路径,如“../admin/abc.aspx” /// </summary> public static string ToRelativePathForPage(this 通用扩展.PathString o) { var s = o.Value; // 根目录虚拟路径 string virtualPath = WebSite变量.Current.Request.ApplicationPath; // 根目录绝对路径 string pathRooted = HostingEnvironment.MapPath(virtualPath); // 页面虚拟路径 string pageVirtualPath = WebSite变量.Current.Request.Path; if (!Path.IsPathRooted(s) || s.IndexOf(pathRooted) == -1) { throw new Exception("路径“{0}”不是绝对路径或不位于当前虚拟Web服务器目录内".FormatWith(s)); } // 转换成相对路径 //(测试发现,pathRooted 在 VS2005 自带的服务器跟在IIS下根目录或者虚拟目录运行似乎不一样, // 有此地方后面会加"\", 有些则不会, 为保险起见判断一下) if (pathRooted.Substring(pathRooted.Length - 1, 1) == "\\") { s = s.Replace(pathRooted, "/"); } else { s = s.Replace(pathRooted, ""); } string relativePath = s.Replace("\\", "/"); string[] pageNodes = pageVirtualPath.Split('/'); // 减去最后一个页面和前面一个 "" 值 int pageNodesCount = pageNodes.Length - 2; for (int i = 0; i < pageNodesCount; i++) { relativePath = "/.." + relativePath; } if (pageNodesCount > 0) { // 如果存在 ".." , 则把最前面的 "/" 去掉 relativePath = relativePath.Substring(1, relativePath.Length - 1); } return(relativePath); }
/// <summary> /// 将指向当前Web站点下的绝对路径转换为虚拟服务器路径,如:“~/admin/abc.aspx” /// </summary> public static ServerPathString ToServerPath(this 通用扩展.PathString o) { var s = o.Value; string pathRooted = HostingEnvironment.MapPath("~/"); if (!Path.IsPathRooted(s) || s.IndexOf(pathRooted) == -1) { throw new Exception("路径“{0}”不是绝对路径或不位于当前虚拟Web服务器目录内".FormatWith(s)); } if (pathRooted.Substring(pathRooted.Length - 1, 1) == "\\") { s = s.Replace(pathRooted, "~/"); } else { s = s.Replace(pathRooted, "~"); } string relativePath = s.Replace("\\", "/"); return(relativePath.AsServerPathString()); }