2013-08-07 51 views

回答

2

另一種解決辦法是結合使用Html Agility Pack用自己的標籤白名單:

using System; 
using System.IO; 
using System.Text; 
using System.Linq; 
using System.Collections.Generic; 
using HtmlAgilityPack; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var whiteList = new[] 
      { 
       "#comment", "html", "head", 
       "title", "body", "img", "p", 
       "a" 
      }; 
     var html = File.ReadAllText("input.html"); 
     var doc = new HtmlDocument(); 
     doc.LoadHtml(html); 
     var nodesToRemove = new List<HtmlAgilityPack.HtmlNode>(); 
     var e = doc 
      .CreateNavigator() 
      .SelectDescendants(System.Xml.XPath.XPathNodeType.All, false) 
      .GetEnumerator(); 
     while (e.MoveNext()) 
     { 
      var node = 
       ((HtmlAgilityPack.HtmlNodeNavigator)e.Current) 
       .CurrentNode; 
      if (!whiteList.Contains(node.Name)) 
      { 
       nodesToRemove.Add(node); 
      } 
     } 
     nodesToRemove.ForEach(node => node.Remove()); 
     var sb = new StringBuilder(); 
     using (var w = new StringWriter(sb)) 
     { 
      doc.Save(w); 
     } 
     Console.WriteLine(sb.ToString()); 
    } 
} 
7

令人驚訝的是微軟在4.2.1版本在4.2 XSS庫可怕的過度補償的安全漏洞和現在還沒有一年後更新。當我讀某人在某處發表評論時,應該將GetSafeHtmlFragment方法重命名爲StripHtml

我結束了使用HtmlSanitizer librarythis related SO issue建議。我喜歡它通過NuGet作爲一個包提供。

這個庫基本實現了現在接受的答案使用白名單方式的變化。但它基於CsQuery而不是HTML Agility庫。該軟件包還提供了一些其他選項,例如可以保留樣式信息(例如HTML屬性)。使用這個庫導致我的項目中的代碼如下所示,至少 - 比接受的答案少得多的代碼:)。

using Html; 

... 

var sanitizer = new HtmlSanitizer(); 
sanitizer.AllowedTags = new List<string> { "p", "ul", "li", "ol", "br" }; 
string sanitizedHtml = sanitizer.Sanitize(htmlString); 
相關問題