写一个页面基类BasePage.cs,其它Aspx继承此BasePage,实现将"~"路径转换成客户端能识别的绝对路径。
如:~/admin/Default.aspx 将被自动转换成 domain/admin/Default.aspx
代码如下:
public class BasePage : System.Web.UI.Page { protected override void Render(HtmlTextWriter writer) { StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter); base.Render(htmlWriter); htmlWriter.Flush(); htmlWriter.Close(); string html = stringWriter.ToString(); #region 转换相对路径 MatchCollection collection = Regex.Matches(html, "<(a|link|img|script|input|form).[^>]*(href|src|action)=(\"|'|)(.[^\"']*)(\"|'|)[^>]*>", RegexOptions.IgnoreCase); foreach (Match match in collection) { string url = match.Groups[match.Groups.Count - 2].Value; if (url.IndexOf("~") != -1) { string newurl = this.Page.ResolveUrl(url); html = html.Replace(url, newurl); } } #endregion writer.Write(html); } }