A potentially dangerous Request.Form value was detected from the client

前端 未结 30 2141
刺人心
刺人心 2020-11-21 05:24

Every time a user posts something containing < or > in a page in my web application, I get this exception thrown.

I don\'t want to go

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 05:49

    I found a solution that uses JavaScript to encode the data, which is decoded in .NET (and doesn't require jQuery).

    • Make the textbox an HTML element (like textarea) instead of an ASP one.
    • Add a hidden field.
    • Add the following JavaScript function to your header.

      function boo() { targetText = document.getElementById("HiddenField1"); sourceText = document.getElementById("userbox"); targetText.value = escape(sourceText.innerText); }

    In your textarea, include an onchange that calls boo():

    
    

    Finally, in .NET, use

    string val = Server.UrlDecode(HiddenField1.Value);
    

    I am aware that this is one-way - if you need two-way you'll have to get creative, but this provides a solution if you cannot edit the web.config

    Here's an example I (MC9000) came up with and use via jQuery:

    $(document).ready(function () {
    
        $("#txtHTML").change(function () {
            var currentText = $("#txtHTML").text();
            currentText = escape(currentText); // Escapes the HTML including quotations, etc
            $("#hidHTML").val(currentText); // Set the hidden field
        });
    
        // Intercept the postback
        $("#btnMyPostbackButton").click(function () {
            $("#txtHTML").val(""); // Clear the textarea before POSTing
                                   // If you don't clear it, it will give you
                                   // the error due to the HTML in the textarea.
            return true; // Post back
        });
    
    
    });
    

    And the markup:

    
    
    
    

    This works great. If a hacker tries to post via bypassing JavaScript, they they will just see the error. You can save all this data encoded in a database as well, then unescape it (on the server side), and parse & check for attacks before displaying elsewhere.

提交回复
热议问题