public static string FormatCompleteUrl(string content) { string pattern = "src=[\"']\\s*(/[^\"']*)\\s*[\"']"; string pattern2 = "href=[\"']\\s*(/[^\"']*)\\s*[\"']"; string str = WebUtility.HostPath(HttpContext.Current.Request.Url); content = Regex.Replace(content, pattern, "src=\"" + str + "$1\"", RegexOptions.IgnoreCase | RegexOptions.Compiled); content = Regex.Replace(content, pattern2, "href=\"" + str + "$1\"", RegexOptions.IgnoreCase | RegexOptions.Compiled); return(content); }
public static string CleanHtml(string rawHtml, TrustedHtmlLevel level) { if (string.IsNullOrEmpty(rawHtml)) { return(rawHtml); } HtmlDocument htmlDocument = new HtmlDocument { OptionAutoCloseOnEnd = true, OptionWriteEmptyNodes = true }; TrustedHtml trustedHtml = new TrustedHtml();// DIContainer.Resolve<TrustedHtml>(); switch (level) { case TrustedHtmlLevel.Basic: trustedHtml = trustedHtml.Basic(); break; case TrustedHtmlLevel.HtmlEditor: trustedHtml = trustedHtml.HtmlEditor(); break; } htmlDocument.LoadHtml(rawHtml); HtmlNodeCollection htmlNodeCollection = htmlDocument.DocumentNode.SelectNodes("//*"); if (htmlNodeCollection != null) { string host = string.Empty; if (HttpContext.Current != null) { host = WebUtility.HostPath(HttpContext.Current.Request.Url); } System.Collections.Generic.Dictionary <string, string> enforcedAttributes; htmlNodeCollection.ToList <HtmlNode>().ForEach(delegate(HtmlNode n) { if (trustedHtml.IsSafeTag(n.Name)) { n.Attributes.ToList <HtmlAttribute>().ForEach(delegate(HtmlAttribute attr) { if (!trustedHtml.IsSafeAttribute(n.Name, attr.Name, attr.Value)) { attr.Remove(); return; } if (attr.Value.StartsWith("javascirpt:", System.StringComparison.InvariantCultureIgnoreCase)) { attr.Value = "javascirpt:;"; } }); enforcedAttributes = trustedHtml.GetEnforcedAttributes(n.Name); if (enforcedAttributes != null) { foreach (System.Collections.Generic.KeyValuePair <string, string> current in enforcedAttributes) { if (!( from a in n.Attributes select a.Name).Contains(current.Key)) { n.Attributes.Add(current.Key, current.Value); } else { n.Attributes[current.Key].Value = current.Value; } } } if (n.Name == "a" && n.Attributes.Contains("href")) { string value = n.Attributes["href"].Value; if (value.StartsWith("http://") && !value.ToLowerInvariant().StartsWith(host.ToLower())) { if (!( from a in n.Attributes select a.Name).Contains("rel")) { n.Attributes.Add("rel", "nofollow"); return; } if (n.Attributes["rel"].Value != "fancybox") { n.Attributes["rel"].Value = "nofollow"; return; } } } } else { if (trustedHtml.EncodeHtml) { n.HtmlEncode = true; return; } n.RemoveTag(); } }); } return(htmlDocument.DocumentNode.WriteTo()); }