C# 實現escape功能


Js段調用escape,可以解決掉很多特殊字符的顯示處理,但是如果你需要在后台處理的時候,需要轉換,不是轉義,比如說你是在前台方法里面顯示一段內容,比如:onmouseover=\"tooltip.show('aaaa')\"; 但是如果這個時候aaa中間有個單引號,如:onmouseover=\"tooltip.show('aaa'a')\";那到前台處理的時候就會出問題了。處理方法如下:

  chr(39) '  轉換后就是 '如此轉換后還需要用HttpUtility.HtmlEncode 

onmouseover=\"tooltip.show('" + HttpUtility.HtmlEncode(EscapeAndRemoveXSS(strDisplayValue)) + "')\"

public static string EscapeAndRemoveXSS(object objInput)
{
      StringBuilder sbdOutput = new StringBuilder();

if (objInput != null)
{
StringBuilder sbdInput = new StringBuilder(objInput.ToString());
for (int intIndex = 0; intIndex < sbdInput.Length; intIndex++)
{
char chrInput = sbdInput[intIndex];
int intChar = System.Convert.ToInt32(chrInput);
//We will encode every characters except "A-Z", "a-z", "0-9", "&", "#", ";", "\", " " by default
if (intChar == 32 || intChar == 35 || intChar == 38  || (intChar >= 48 && intChar <= 57) ||
intChar == 59 || (intChar >= 65 && intChar <= 90) || intChar == 92 || (intChar >= 97 && intChar <= 122) || intChar == 58 || intChar == 33)
{
sbdOutput.Append(chrInput);
}

else
{
//strOutput = strOutput + chrInput;
sbdOutput.Append("&#" + intChar + ";");
}
}
}
return sbdOutput.ToString()

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM