徹底解決“從客戶端中檢測到有潛在危險的Request.Form值”


    類似設置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, "&lt;")
              .replace(/>/g, "&gt;");
}

function decodeHtml(val) {
    return val.replace(/&amp;/g, "&")
              .replace(/&lt;/g, "<")
              .replace(/&gt;/g, ">")
              .replace(/&#039;/g, "'")
              .replace(/&quot;/g, "\"");
}

    說明:上面的encodeHtml和decodeHtml方法有點繞人,因為這兩個方法不對稱,encodeHtml方法少了.replace(/'/g, "&#039;").replace(/\"/g, "&quot;")。編碼的目的,是為了繞過驗證,而導致驗證不通過的原因是因為某些html標簽,也就是說當字符串中含有<、>、&#039;之類的標識時,就會驗證不通過,所以只需把&、<、>這三個替換掉就可以了。如果加上.replace(/'/g, "&#039;").replace(/\"/g, "&quot;"),則又會導致出現$#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("&", "&amp;")
                       .Replace("<", "&lt;")
                       .Replace(">", "&gt;")
                       .Replace("'", "&#039;")
                       .Replace("\"", "&quot;");
        }
        #endregion

        #region html解碼
        /// <summary>
        /// html解碼
        /// </summary>
        public static string DecodeHtml(string html)
        {
            return html.Replace("&amp;", "&")
                       .Replace("&lt;", "<")
                       .Replace("&gt;", ">")
                       .Replace("&#039;", "'")
                       .Replace("&quot;", "\"");
        }
        #endregion

    }
}
View Code

 




免責聲明!

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



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