類似設置validateRequest="false"的方法不推薦,因為應用程序需要顯式檢查所有輸入,不方便。
1、前端使用encodeHtml函數對字符串進行編碼,例:
var editor = $("textarea[name='editorValue']"); $("#contents").val(encodeHtml(editor.val())); var formData = new FormData($("#frm")[0]);
2、后端使用HtmlUtil.DecodeHtml方法進行解碼,例:
model.contents = HtmlUtil.DecodeHtml(model.contents);
3、View頁面展示在編輯器中,例:
ue.addListener('ready', function (editor) { var contents = decodeHtml("@content.contents"); ue.setContent(contents); });
JS方法decodeHtml代碼:
function encodeHtml(val) { return val.replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">"); } function decodeHtml(val) { return val.replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/'/g, "'") .replace(/"/g, "\""); }
說明:上面的encodeHtml和decodeHtml方法有點繞人,因為這兩個方法不對稱,encodeHtml方法少了.replace(/'/g, "'").replace(/\"/g, """)。編碼的目的,是為了繞過驗證,而導致驗證不通過的原因是因為某些html標簽,也就是說當字符串中含有<、>、'之類的標識時,就會驗證不通過,所以只需把&、<、>這三個替換掉就可以了。如果加上.replace(/'/g, "'").replace(/\"/g, """),則又會導致出現$#039;從而導致驗證不通過,所以encodeHtml方法只替換3個。但解碼多替換了兩個,這是必需的,否則<span style="font-size:20px;"></span>在百度編輯器中顯示會變成<span></span>從而造成style樣式的丟失。
HtmlUtil.DecodeHtml方法代碼:

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Common.Utils { /// <summary> /// HTML工具類 /// </summary> public class HtmlUtil { #region html編碼 /// <summary> /// html編碼 /// </summary> public static string EncodeHtml(string html) { return html.Replace("&", "&") .Replace("<", "<") .Replace(">", ">") .Replace("'", "'") .Replace("\"", """); } #endregion #region html解碼 /// <summary> /// html解碼 /// </summary> public static string DecodeHtml(string html) { return html.Replace("&", "&") .Replace("<", "<") .Replace(">", ">") .Replace("'", "'") .Replace(""", "\""); } #endregion } }