2011-08-10 6 views
1

実行時に作成されるasp Webページがあります。静的なテンプレートがありますが、ページの要素とその情報は、他のアプリケーションページのユーザー入力に基づいて作成されます。 また、ユーザーはhtml形式でデータを挿入することもできます。ユーザーがhtml形式でデータを入力してもhtmlタグを閉じるなどの忘れた場合に問題が発生します。 アプリケーションでクラッシュすることはありませんが、ページを表示する場合はブラウザが混乱します。 ページの作成時に、実行時にユーザー入力をクリーンアップまたは解析する必要があります。 これを行う方法を知っている人はいますか? ASP.netのライブラリや関数はありますか?ASP.NETアプリケーションのHTMLのクリーンアップ方法

ありがとうございました。

答えて

0

を使用してHTMLを読み込んでから書き出して、クリーンアップします。

使用例は

/// <summary> 
    /// Tidy up a partial html string. 
    /// </summary> 
    /// <param name="html">Html string to tidy.</param> 
    /// <returns>A cleaned html string.</returns> 
    /// <remarks>If <paramref name="html" /> contains a body tag, 
    /// it returns only first body contents.</remarks> 
    public static string TidyPartial(string html) 
    { 
     var doc = new HtmlDocument(); 
     doc.OptionFixNestedTags = true; 
     // If you wish it to be xhtml like (does not suffice to 
     // enforce w3c xhtml validity). 
     doc.OptionOutputAsXml = true; 
     doc.LoadHtml(html); 

     var body = doc.DocumentNode.SelectSingleNode("//body"); 
     var cleanedHtml = (body != null) ? 
      body.InnerHtml : doc.DocumentNode.InnerHtml; 
     return cleanedHtml; 
    } 
0

正しくHTMLをフォーマットするTidy.netを使用してみてください(HtmlAgilityPack名前空間を使用して忘れないでください)。 tidy.net

var document = new Tidy(); 
var messageCollection = new TidyMessageCollection(); 
document.Options.DocType = DocType.Omit; 
document.Options.Xhtml = true; 
document.Options.CharEncoding = CharEncoding.UTF8; 
document.Options.LogicalEmphasis = true; 
document.Options.MakeClean = false; 
document.Options.QuoteNbsp = false; 
document.Options.SmartIndent = false; 
document.Options.IndentContent = false; 
document.Options.TidyMark = false; 
document.Options.DropFontTags = false; 
document.Options.QuoteAmpersand = true; 
document.Options.DropEmptyParas = true; 
using (var input = new MemoryStream()) 
{ 
    using (var output = new MemoryStream()) 
    { 
     byte[] array = Encoding.UTF8.GetBytes(xmlResult); 
     input.Write(array, 0, array.Length); 
     input.Position = 0; 
     document.Parse(input, output, messageCollection); 
     return Encoding.UTF8.GetString(output.ToArray()); 
    } 
} 

ユーザーがページにHTMLを追加することができたときに、クロスサイドスクリプティングの注意する必要があります。 この投稿を見てSanitising HTML with C# and Tidy

関連する問題