簡體   English   中英

HTTPModule問題:替換頁面渲染上的文本

[英]HTTPModule Issue: Replacing Text On Page Render

我正在編寫一個HTTPModule,它將搜索出網頁中的所有mailto鏈接,混淆電子郵件地址和尾隨參數,然后將新混淆的字符串放回HTML文檔中。 然后,我使用一些JavaScript在瀏覽器中取消混淆mailto鏈接,以便當用戶單擊鏈接時它可以正常運行。

到目前為止,我已經成功地對信息進行了模糊處理和無混淆處理。 我遇到的問題是將混淆后的字符串放回到流中。 如果一個mailto鏈接僅在文檔中出現一次,那么它會完美地將混淆后的字符串替換為mailto鏈接,但是如果有多個mailto鏈接,則這些字符串的放置似乎是隨機的。 我很確定它與正則表達式匹配索引的位置有關,因為該函數在匹配中循環,並基本上增加了流中HTML的長度。 我將在此處發布一些經過策略編輯的代碼,以查看是否有人對如何正確定位混淆字符串的位置有想法。

我還將發布我為混淆字符串所做的工作,以期對嘗試做相同事情的人有所幫助。

public override void Write(byte[] buffer, int offset, int count)
  {
      byte[] data = new byte[count];
      Buffer.BlockCopy(buffer, offset, data, 0, count);
      string html = System.Text.Encoding.Default.GetString(buffer);

      //--- Work on the HTML from the page. We want to pass it through the 
      //--- obfusication function before it is sent to the browser.
      html = html.Replace(html, obfuscate(html));

      byte[] outdata = System.Text.Encoding.Default.GetBytes(html);
      _strmHTML.Write(outdata, 0, outdata.GetLength(0));
  }


protected string obfuscate(string input)
    {

      //--- Declarations
      string email = string.Empty;
      string obsEmail = string.Empty;
      string matchedEMail = string.Empty;
      int matchIndex = 0;
      int matchLength = 0;

      //--- This is a REGEX to grab any "a href=mailto" tags in the document.
      MatchCollection matches = Regex.Matches(input, @"<a href=""mailto:[a-zA-Z0-9\.,|\-|_@?= &]*"">", RegexOptions.Singleline | RegexOptions.IgnoreCase);

      //--- Because of the nature of doing a match search with regex, we must now loop through the results
      //--- of the MatchCollection.
        foreach (Match match in matches)
        {

            //--- Get the match string
            matchedEMail = match.ToString();
            matchIndex = match.Index;
            matchLength = match.Length;

            //--- Obfusicate the matched string.
            obsEmail = obfusucateEmail(@match.Value.ToString());

           //--- Reform the entire HTML stream. THis has to be added back in at the right point.
           input = input.Substring(0, matchIndex) + obsEmail + input.Substring(matchIndex + matchLength);                 
        }

      //--- Return the obfuscated result.
      return input;
    }



protected string obfusucateEmail(string input)
  {

      //--- Declarations
      string email = string.Empty;
      string obsEmail = string.Empty;

      //--- Reset these value, in case we find more than one match.
      email = string.Empty;
      obsEmail = string.Empty;

      //--- Get the email address out of the array
      email = @input;

      //--- Clean up the string. We need to get rid of the beginning of the tag, and the end >. First,
      //--- let's flush out all quotes.
      email = email.Replace("\"", "");

      //--- Now, let's replace the beginning of the tag.
      email = email.Replace("<a href=mailto:", "");

      //--- Finally, let's get rid of the closing tag.
      email = email.Replace(">", "");


      //--- Now, we have a cleaned mailto string. Let's obfusicate it.
      Array matcharray = email.ToCharArray();

      //--- Loop through the CharArray and encode each letter.
      foreach (char letter in matcharray)
      {
          //Convert each letter of the address to the corresponding ASCII code.
          //Add XX to each value to break the direct ASCII code to letter mapping. We'll deal
          // with subtracting XX from each number on the JavaScript side.
          obsEmail += Convert.ToInt32((letter) + 42).ToString() + "~";
      }

      //--- Before we return the obfusicated value, we need to reform the tag.
      //--- Remember, up above, we stripped all this out. Well now, we need 
      //--- to add it again.
      obsEmail = "<a href=\"mailto:" + obsEmail + "\">";

      return obsEmail;
  }

我感謝任何想法!

謝謝,邁克

您可以做的另一件事是在正則表達式中使用匹配評估器....

protected string ObfuscateUsingMatchEvaluator(string input)
{
            var re = new Regex(@"<a href=""mailto:[a-zA-Z0-9\.,|\-|_@?= &]*"">",            RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return re.Replace(input, DoObfuscation);

}

protected string DoObfuscation(Match match)
{
       return obfusucateEmail(match.Value);
}

根據您的性能需求(取決於您的文檔大小),您可以考慮使用HTML Agility Pack而不是正則表達式來解析和處理HTML。 您可以使用Linq to Objects或XPath來標識所有mailto標記。

您應該能夠修改下面的示例( 在codeplex Wiki頁面上 )以找到mailto標記:

HtmlDocument doc = new HtmlDocument();
 doc.Load("file.htm");
 foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])
 {
    HtmlAttribute att = link["href"];
    if (att.Value.StartsWith("mailto:") EncryptValue(att);
 }
 doc.Save("file.htm");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM