<p>Every time a user posts something containing <code>&lt;</code> or <code>&gt;</code> in a page in my web application, I get this exception thrown.</p>

<p>I don't want to go into the discussion about the smartness of throwing an exception or crashing an entire web application because somebody entered a character in a text box, but I am looking for an elegant way to handle this.</p>

<p>Trapping the exception and showing</p>

<blockquote>
  <p>An error has occurred please go back and re-type your entire form again, but this time please do not use &lt;</p>
</blockquote>

<p>doesn't seem professional enough to me.</p>

<p>Disabling post validation (<code>validateRequest="false"</code>) will definitely avoid this error, but it will leave the page vulnerable to a number of attacks.</p>

<p>Ideally: When a post back occurs containing HTML restricted characters, that posted value in the Form collection will be automatically HTML encoded.
So the <code>.Text</code> property of my text-box will be <code>something &amp; lt; html &amp; gt;</code></p>

<p>Is there a way I can do this from a handler?</p>

[{'answer_id': 82121, 'author': 'Pavel Chuchuva', 'author_id': 14131, 'author_profile': 'https://Stackoverflow.com/users/14131', 'pm_score': 6, 'selected': False, 'text': '<p>You can <a href="https://learn.microsoft.com/en-us/dotnet/api/system.web.httpserverutility.htmlencode" rel="noreferrer">HTML encode</a> text box content, but unfortunately that won\'t stop the exception from happening. In my experience there is no way around, and you have to disable page validation. By doing that you\'re saying: "I\'ll be careful, I promise."</p>\n'}, {'answer_id': 82136, 'author': 'bastos.sergio', 'author_id': 12772, 'author_profile': 'https://Stackoverflow.com/users/12772', 'pm_score': 2, 'selected': False, 'text': '<p>You should use the Server.HtmlEncode method to protect your site from dangerous input.</p>\n\n<p><a href="http://www.asp.net/learn/whitepapers/request-validation/" rel="nofollow noreferrer">More info here</a></p>\n'}, {'answer_id': 82170, 'author': 'JacquesB', 'author_id': 7488, 'author_profile': 'https://Stackoverflow.com/users/7488', 'pm_score': 11, 'selected': True, 'text': '<p>I think you are attacking it from the wrong angle by trying to encode all posted data.</p>\n<p>Note that a &quot;<code>&lt;</code>&quot; could also come from other outside sources, like a database field, a configuration, a file, a feed and so on.</p>\n<p>Furthermore, &quot;<code>&lt;</code>&quot; is not inherently dangerous. It\'s only dangerous in a specific context: when writing strings that haven\'t been encoded to HTML output (because of XSS).</p>\n<p>In other contexts different sub-strings are dangerous, for example, if you write an user-provided URL into a link, the sub-string &quot;<code>javascript:</code>&quot; may be dangerous. The single quote character on the other hand is dangerous when interpolating strings in SQL queries, but perfectly safe if it is a part of a name submitted from a form or read from a database field.</p>\n<p>The bottom line is: you can\'t filter random input for dangerous characters, because any character may be dangerous under the right circumstances. You should encode at the point where some specific characters may become dangerous because they cross into a different sub-language where they have special meaning. When you write a string to HTML, you should encode characters that have special meaning in HTML, using Server.HtmlEncode. If you pass a string to a dynamic SQL statement, you should encode different characters (or better, let the framework do it for you by using prepared statements or the like)..</p>\n<p><em>When</em> you are sure you HTML-encode everywhere you pass strings to HTML, then set <code>ValidateRequest=&quot;false&quot;</code> in the <code>&lt;%@ Page ... %&gt;</code> directive in your <code>.aspx</code> file(s).</p>\n<p>In .NET 4 you may need to do a little more. Sometimes it\'s necessary to also add <code>&lt;httpRuntime requestValidationMode=&quot;2.0&quot; /&gt;</code> to web.config (<a href="http://www.asp.net/%28S%28ywiyuluxr3qb2dfva1z5lgeg%29%29/learn/whitepapers/aspnet4/breaking-changes/" rel="noreferrer">reference</a>).</p>\n'}, {'answer_id': 82174, 'author': 'blowdart', 'author_id': 2525, 'author_profile': 'https://Stackoverflow.com/users/2525', 'pm_score': 4, 'selected': False, 'text': '<p>I guess you could do it in a module; but that leaves open some questions; what if you want to save the input to a database? Suddenly because you\'re saving encoded data to the database you end up trusting input from it which is probably a bad idea. Ideally you store raw unencoded data in the database and the encode every time.</p>\n\n<p>Disabling the protection on a per page level and then encoding each time is a better option.</p>\n\n<p>Rather than using Server.HtmlEncode you should look at the newer, more complete <a href="http://blogs.msdn.com/ace_team/archive/2006/11/20/microsoft-anti-cross-site-scripting-library-v1-5-is-done.aspx" rel="nofollow noreferrer">Anti-XSS library</a> from the Microsoft ACE team.</p>\n'}, {'answer_id': 82179, 'author': 'Paweł Hajdan', 'author_id': 9403, 'author_profile': 'https://Stackoverflow.com/users/9403', 'pm_score': 3, 'selected': False, 'text': '<p>As long as these are <strong>only</strong> "&lt;" and ">" (and not the double quote itself) characters and you\'re using them in context like &lt;input value="<em>this</em>" /&gt;, you\'re safe (while for &lt;textarea&gt;<em>this one</em>&lt;/textarea&gt; you would be vulnerable of course). That may simplify your situation, but for <strong>anything</strong> more use one of other posted solutions.</p>\n'}, {'answer_id': 82203, 'author': 'woany', 'author_id': 15623, 'author_profile': 'https://Stackoverflow.com/users/15623', 'pm_score': 3, 'selected': False, 'text': '<p>Disable the page validation if you really need the special characters like, <code>&gt;</code>, , <code>&lt;</code>, etc. Then ensure that when the user input is displayed, the data is HTML-encoded. </p>\n\n<p>There is a security vulnerability with the page validation, so it can be bypassed. Also the page validation shouldn\'t be solely relied on.</p>\n\n<p>See: <a href="http://web.archive.org/web/20080913071637/http://www.procheckup.com:80/PDFs/bypassing-dot-NET-ValidateRequest.pdf" rel="nofollow noreferrer">http://web.archive.org/web/20080913071637/http://www.procheckup.com:80/PDFs/bypassing-dot-NET-ValidateRequest.pdf</a></p>\n'}, {'answer_id': 82243, 'author': 'Captain Toad', 'author_id': 15664, 'author_profile': 'https://Stackoverflow.com/users/15664', 'pm_score': 3, 'selected': False, 'text': "<p>If you're just looking to tell your users that &lt; and > are not to be used BUT, you don't want the entire form processed/posted back (and lose all the input) before-hand could you not simply put in a validator around the field to screen for those (and maybe other potentially dangerous) characters?</p>\n"}, {'answer_id': 83949, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>Please bear in mind that some .NET controls will automatically HTML encode the output. For instance, setting the .Text property on a TextBox control will automatically encode it. That specifically means converting <code>&lt;</code> into <code>&amp;lt;</code>, <code>&gt;</code> into <code>&amp;gt;</code> and <code>&amp;</code> into <code>&amp;amp;</code>. So be wary of doing this...</p>\n\n<pre><code>myTextBox.Text = Server.HtmlEncode(myStringFromDatabase); // Pseudo code\n</code></pre>\n\n<p>However, the .Text property for HyperLink, Literal and Label won\'t HTML encode things, so wrapping Server.HtmlEncode(); around anything being set on these properties is a must if you want to prevent <code>&lt;script&gt; window.location = "http://www.google.com"; &lt;/script&gt;</code> from being output into your page and subsequently executed.</p>\n\n<p>Do a little experimenting to see what gets encoded and what doesn\'t.</p>\n'}, {'answer_id': 436247, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>If you don\'t want to disable ValidateRequest you need to implement a JavaScript function in order to avoid the exception. It is not the best option, but it works.</p>\n\n<pre><code>function AlphanumericValidation(evt)\n{\n    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :\n        ((evt.which) ? evt.which : 0));\n\n    // User type Enter key\n    if (charCode == 13)\n    {\n        // Do something, set controls focus or do anything\n        return false;\n    }\n\n    // User can not type non alphanumeric characters\n    if ( (charCode &lt;  48)                     ||\n         (charCode &gt; 122)                     ||\n         ((charCode &gt; 57) &amp;&amp; (charCode &lt; 65)) ||\n         ((charCode &gt; 90) &amp;&amp; (charCode &lt; 97))\n       )\n    {\n        // Show a message or do something\n        return false;\n    }\n}\n</code></pre>\n\n<p>Then in code behind, on the PageLoad event, add the attribute to your control with the next code:</p>\n\n<pre><code>Me.TextBox1.Attributes.Add("OnKeyPress", "return AlphanumericValidation(event);")\n</code></pre>\n'}, {'answer_id': 1540976, 'author': 'Zack Peterson', 'author_id': 83, 'author_profile': 'https://Stackoverflow.com/users/83', 'pm_score': 9, 'selected': False, 'text': '<p>There\'s a different solution to this error if you\'re using ASP.NET MVC:</p>\n\n<ul>\n<li><a href="http://jwwishart.wordpress.com/2009/06/22/asp-net-mvc-pages-validaterequestfalse-doesnt-work/" rel="noreferrer">ASP.NET MVC – pages validateRequest=false doesn’t work?</a></li>\n<li><a href="https://stackoverflow.com/questions/807662/why-is-validateinputfalse-not-working">Why is ValidateInput(False) not working?</a></li>\n<li><a href="https://web.archive.org/web/20160327063049/http://weblogs.asp.net:80/rashid/asp-net-mvc-rc1-validateinput-a-potential-dangerous-request-and-the-pitfall" rel="noreferrer">ASP.NET MVC RC1, VALIDATEINPUT, A POTENTIAL DANGEROUS REQUEST AND THE PITFALL</a></li>\n</ul>\n\n<p>C# sample:</p>\n\n<pre><code>[HttpPost, ValidateInput(false)]\npublic ActionResult Edit(FormCollection collection)\n{\n    // ...\n}\n</code></pre>\n\n<p>Visual Basic sample:</p>\n\n<pre><code>&lt;AcceptVerbs(HttpVerbs.Post), ValidateInput(False)&gt; _\nFunction Edit(ByVal collection As FormCollection) As ActionResult\n    ...\nEnd Function\n</code></pre>\n'}, {'answer_id': 1563330, 'author': 'BenMaddox', 'author_id': 38698, 'author_profile': 'https://Stackoverflow.com/users/38698', 'pm_score': 6, 'selected': False, 'text': '<p>You can catch that error in Global.asax.  I still want to validate, but show an appropriate message.   On the blog listed below, a sample like this was available.  </p>\n\n<pre><code>    void Application_Error(object sender, EventArgs e)\n    {\n        Exception ex = Server.GetLastError();\n\n        if (ex is HttpRequestValidationException)\n        {\n            Response.Clear();\n            Response.StatusCode = 200;\n            Response.Write(@"[html]");\n            Response.End();\n        }\n    }\n</code></pre>\n\n<p>Redirecting to another page also seems like a reasonable response to the exception.</p>\n\n<p><a href="http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html" rel="noreferrer">http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html</a></p>\n'}, {'answer_id': 3368769, 'author': 'JordanC', 'author_id': 172330, 'author_profile': 'https://Stackoverflow.com/users/172330', 'pm_score': 8, 'selected': False, 'text': '<p>If you are on .NET 4.0 make sure you add this in your <em>web.config</em> file inside the <code>&lt;system.web&gt;</code> tags:</p>\n\n<pre><code>&lt;httpRuntime requestValidationMode="2.0" /&gt;\n</code></pre>\n\n<hr>\n\n<p>In .NET 2.0, request validation only applied to <code>aspx</code> requests. In .NET 4.0 this was expanded to include <strong>all</strong> requests. You can revert to <em>only</em> performing XSS validation when processing <code>.aspx</code> by specifying:</p>\n\n<pre><code>requestValidationMode="2.0"\n</code></pre>\n\n<p>You can disable request validate <em>entirely</em> by specifying:</p>\n\n<pre><code>validateRequest="false"\n</code></pre>\n'}, {'answer_id': 4113591, 'author': 'gligoran', 'author_id': 227613, 'author_profile': 'https://Stackoverflow.com/users/227613', 'pm_score': 6, 'selected': False, 'text': '<p>The previous answers are great, but nobody said how to exclude a single field from being validated for HTML/JavaScript injections. I don\'t know about previous versions, but in MVC3 Beta you can do this:</p>\n\n<pre><code>[HttpPost, ValidateInput(true, Exclude = "YourFieldName")]\npublic virtual ActionResult Edit(int id, FormCollection collection)\n{\n    ...\n}\n</code></pre>\n\n<p>This still validates all the fields except for the excluded one. The nice thing about this is that your validation attributes still validate the field, but you just don\'t get the "A potentially dangerous Request.Form value was detected from the client" exceptions.</p>\n\n<p>I\'ve used this for validating a regular expression. I\'ve made my own ValidationAttribute to see if the regular expression is valid or not. As regular expressions can contain something that looks like a script I applied the above code - the regular expression is still being checked if it\'s valid or not, but not if it contains scripts or HTML.</p>\n'}, {'answer_id': 4313998, 'author': 'ranthonissen', 'author_id': 403259, 'author_profile': 'https://Stackoverflow.com/users/403259', 'pm_score': 6, 'selected': False, 'text': '<p>In ASP.NET MVC you need to set requestValidationMode="2.0" and validateRequest="false" in web.config, and apply a ValidateInput attribute to your controller action:</p>\n\n<pre><code>&lt;httpRuntime requestValidationMode="2.0"/&gt;\n\n&lt;configuration&gt;\n    &lt;system.web&gt;\n        &lt;pages validateRequest="false" /&gt;\n    &lt;/system.web&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>[Post, ValidateInput(false)]\npublic ActionResult Edit(string message) {\n    ...\n}\n</code></pre>\n'}, {'answer_id': 7306222, 'author': 'Anthony Johnston', 'author_id': 122232, 'author_profile': 'https://Stackoverflow.com/users/122232', 'pm_score': 9, 'selected': False, 'text': '<p>In ASP.NET MVC (starting in version 3), you can add the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.allowhtmlattribute.aspx" rel="noreferrer"><code>AllowHtml</code></a> attribute to a property on your model.</p>\n\n<p>It allows a request to include HTML markup during model binding by skipping request validation for the property.</p>\n\n<pre><code>[AllowHtml]\npublic string Description { get; set; }\n</code></pre>\n'}, {'answer_id': 9035316, 'author': 'Piercy', 'author_id': 455135, 'author_profile': 'https://Stackoverflow.com/users/455135', 'pm_score': 5, 'selected': False, 'text': '<p>It seems no one has mentioned the below yet, but it fixes the issue for me.  And before anyone says yeah it\'s Visual Basic... yuck.</p>\n\n<pre><code>&lt;%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Example.aspx.vb" Inherits="Example.Example" **ValidateRequest="false"** %&gt;\n</code></pre>\n\n<p>I don\'t know if there are any downsides, but for me this worked amazing.</p>\n'}, {'answer_id': 9237332, 'author': 'Trisped', 'author_id': 641833, 'author_profile': 'https://Stackoverflow.com/users/641833', 'pm_score': 3, 'selected': False, 'text': '<p>You could also use JavaScript\'s <a href="http://www.w3schools.com/jsref/jsref_escape.asp" rel="noreferrer">escape(string)</a> function to replace the special characters.  Then server side use Server.<a href="http://msdn.microsoft.com/en-us/library/hwzhtkke.aspx" rel="noreferrer">URLDecode(string)</a> to switch it back.</p>\n\n<p>This way you don\'t have to turn off input validation and it will be more clear to other programmers that the string may have HTML content.</p>\n'}, {'answer_id': 9711182, 'author': 'Mahdi jokar', 'author_id': 1125430, 'author_profile': 'https://Stackoverflow.com/users/1125430', 'pm_score': 5, 'selected': False, 'text': '<p>In the web.config file, within the  tags, insert the httpRuntime element with the attribute requestValidationMode="2.0". Also add the validateRequest="false" attribute in the pages element.</p>\n\n<p>Example:</p>\n\n<pre><code>&lt;configuration&gt;\n  &lt;system.web&gt;\n   &lt;httpRuntime requestValidationMode="2.0" /&gt;\n  &lt;/system.web&gt;\n  &lt;pages validateRequest="false"&gt;\n  &lt;/pages&gt;\n&lt;/configuration&gt;\n</code></pre>\n'}, {'answer_id': 9739209, 'author': 'magritte', 'author_id': 931545, 'author_profile': 'https://Stackoverflow.com/users/931545', 'pm_score': 3, 'selected': False, 'text': "<p>The other solutions here are nice, however it's a bit of a royal pain in the rear to have to apply [AllowHtml] to every single Model property, especially if you have over 100 models on a decent sized site.</p>\n\n<p>If like me, you want to turn this (IMHO pretty pointless) feature off site wide you can override the Execute() method in your base controller (if you don't already have a base controller I suggest you make one, they can be pretty useful for applying common functionality).</p>\n\n<pre><code>    protected override void Execute(RequestContext requestContext)\n    {\n        // Disable requestion validation (security) across the whole site\n        ValidateRequest = false;\n        base.Execute(requestContext);\n    }\n</code></pre>\n\n<p>Just make sure that you are HTML encoding everything that is pumped out to the views that came from user input (it's default behaviour in ASP.NET MVC 3 with Razor anyway, so unless for some bizarre reason you are using Html.Raw() you shouldn't require this feature.</p>\n"}, {'answer_id': 11530248, 'author': 'Jaider', 'author_id': 480700, 'author_profile': 'https://Stackoverflow.com/users/480700', 'pm_score': 4, 'selected': False, 'text': '<p>In ASP.NET, you can catch the exception and do something about it, such as displaying a friendly message or redirect to another page... Also there is a possibility that you can handle the validation by yourself...</p>\n\n<p>Display friendly message:</p>\n\n<pre><code>protected override void OnError(EventArgs e)\n{\n    base.OnError(e);\n    var ex = Server.GetLastError().GetBaseException();\n    if (ex is System.Web.HttpRequestValidationException)\n    {\n        Response.Clear();\n        Response.Write("Invalid characters."); //  Response.Write(HttpUtility.HtmlEncode(ex.Message));\n        Response.StatusCode = 200;\n        Response.End();\n    }\n}\n</code></pre>\n'}, {'answer_id': 11798616, 'author': 'Ryan', 'author_id': 1574529, 'author_profile': 'https://Stackoverflow.com/users/1574529', 'pm_score': 3, 'selected': False, 'text': '<p>I ended up using JavaScript before each postback to check for the characters you didn\'t want, such as:</p>\n\n<pre><code>&lt;asp:Button runat="server" ID="saveButton" Text="Save" CssClass="saveButton" OnClientClick="return checkFields()" /&gt;\n\nfunction checkFields() {\n    var tbs = new Array();\n    tbs = document.getElementsByTagName("input");\n    var isValid = true;\n    for (i=0; i&lt;tbs.length; i++) {\n        if (tbs(i).type == \'text\') {\n            if (tbs(i).value.indexOf(\'&lt;\') != -1 || tbs(i).value.indexOf(\'&gt;\') != -1) {\n                alert(\'&lt;&gt; symbols not allowed.\');\n                isValid = false;\n            }\n        }\n    }\n    return isValid;\n}\n</code></pre>\n\n<p>Granted my page is mostly data entry, and there are very few elements that do postbacks, but at least their data is retained.</p>\n'}, {'answer_id': 11955698, 'author': 'Leniel Maccaferri', 'author_id': 114029, 'author_profile': 'https://Stackoverflow.com/users/114029', 'pm_score': 3, 'selected': False, 'text': '<p>I was getting this error too.</p>\n\n<p>In my case, a user entered an accented character <code>á</code> in a Role Name (regarding the ASP.NET membership provider).</p>\n\n<p>I pass the role name to a method to grant Users to that role and the <code>$.ajax</code> post request was failing miserably...</p>\n\n<p>I did this to solve the problem:</p>\n\n<p>Instead of</p>\n\n<pre><code>data: { roleName: \'@Model.RoleName\', users: users }\n</code></pre>\n\n<p>Do this</p>\n\n<pre><code>data: { roleName: \'@Html.Raw(@Model.RoleName)\', users: users }\n</code></pre>\n\n<p><code>@Html.Raw</code> did the trick.</p>\n\n<p>I was getting the Role name as HTML value <code>roleName="Cadastro b&amp;#225;s"</code>. This value with HTML entity <code>&amp;#225;</code> was being blocked by ASP.NET MVC. Now I get the <code>roleName</code> parameter value the way it should be: <code>roleName="Cadastro Básico"</code> and ASP.NET MVC engine won\'t block the request anymore.</p>\n'}, {'answer_id': 13589607, 'author': 'Carter Medlin', 'author_id': 324479, 'author_profile': 'https://Stackoverflow.com/users/324479', 'pm_score': 7, 'selected': False, 'text': '<p>For ASP.NET 4.0, you can allow markup as input for specific pages instead of the whole site by putting it all in a <code>&lt;location&gt;</code> element.  This will make sure all your other pages are safe.  You do NOT need to put <code>ValidateRequest="false"</code> in your .aspx page.</p>\n\n<pre><code>&lt;configuration&gt;\n...\n  &lt;location path="MyFolder/.aspx"&gt;\n    &lt;system.web&gt;\n      &lt;pages validateRequest="false" /&gt;\n      &lt;httpRuntime requestValidationMode="2.0" /&gt;\n    &lt;/system.web&gt;\n  &lt;/location&gt;\n...\n&lt;/configuration&gt;\n</code></pre>\n\n<p>It is safer to control this inside your web.config, because you can see at a site level which pages allow markup as input.</p>\n\n<p><strong>You still need to programmatically validate input on pages where request validation is disabled.</strong></p>\n'}, {'answer_id': 14925246, 'author': 'Mike S.', 'author_id': 1937357, 'author_profile': 'https://Stackoverflow.com/users/1937357', 'pm_score': 2, 'selected': False, 'text': "<p>None of the suggestions worked for me.  I did not want to turn off this feature for the whole website anyhow because 99% time I do not want my users placing HTML on web forms.  I just created my own work around method since I'm the only one using this particular application.  I convert the input to HTML in the code behind and insert it into my database.</p>\n"}, {'answer_id': 16224548, 'author': 'flakomalo', 'author_id': 2321524, 'author_profile': 'https://Stackoverflow.com/users/2321524', 'pm_score': 6, 'selected': False, 'text': '<p>The answer to this question is simple:</p>\n\n<pre><code>var varname = Request.Unvalidated["parameter_name"];\n</code></pre>\n\n<p>This would disable validation for the particular request.</p>\n'}, {'answer_id': 16867157, 'author': 'Ady Levy', 'author_id': 2442115, 'author_profile': 'https://Stackoverflow.com/users/2442115', 'pm_score': 3, 'selected': False, 'text': '<p>You can use something like:</p>\n\n<pre><code>var nvc = Request.Unvalidated().Form;\n</code></pre>\n\n<p>Later, <code>nvc["yourKey"]</code> should work.</p>\n'}, {'answer_id': 20450300, 'author': 'Sel', 'author_id': 2706338, 'author_profile': 'https://Stackoverflow.com/users/2706338', 'pm_score': 4, 'selected': False, 'text': '<p>Another solution is:</p>\n\n<pre><code>protected void Application_Start()\n{\n    ...\n    RequestValidator.Current = new MyRequestValidator();\n}\n\npublic class MyRequestValidator: RequestValidator\n{\n    protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)\n    {\n        bool result = base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);\n\n        if (!result)\n        {\n            // Write your validation here\n            if (requestValidationSource == RequestValidationSource.Form ||\n                requestValidationSource == RequestValidationSource.QueryString)\n\n                return true; // Suppress error message\n        }\n        return result;\n    }\n}\n</code></pre>\n'}, {'answer_id': 21427148, 'author': 'A.Dara', 'author_id': 1115537, 'author_profile': 'https://Stackoverflow.com/users/1115537', 'pm_score': 5, 'selected': False, 'text': '<p>For MVC, ignore input validation by adding  </p>\n\n<blockquote>\n  <p>[ValidateInput(false)]</p>\n</blockquote>\n\n<p>above each Action in the Controller.</p>\n'}, {'answer_id': 23415656, 'author': 'Walden Leverich', 'author_id': 2673770, 'author_profile': 'https://Stackoverflow.com/users/2673770', 'pm_score': 2, 'selected': False, 'text': '<p>As indicated in my comment to <a href="https://stackoverflow.com/questions/81991/a-potentially-dangerous-request-form-value-was-detected-from-the-client/20450300#20450300">Sel\'s answer</a>, this is our extension to a custom request validator.</p>\n\n<pre><code>public class SkippableRequestValidator : RequestValidator\n{\n    protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)\n    {\n        if (collectionKey != null &amp;&amp; collectionKey.EndsWith("_NoValidation"))\n        {\n            validationFailureIndex = 0;\n            return true;\n        }\n\n        return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);\n    }\n}\n</code></pre>\n'}, {'answer_id': 25872850, 'author': 'Jason Shuler', 'author_id': 1026711, 'author_profile': 'https://Stackoverflow.com/users/1026711', 'pm_score': 4, 'selected': False, 'text': '<p>I found a solution that uses JavaScript to encode the data, which is decoded in .NET (and doesn\'t require jQuery).</p>\n\n<ul>\n<li>Make the textbox an HTML element (like textarea) instead of an ASP one.</li>\n<li>Add a hidden field.</li>\n<li><p>Add the following JavaScript function to your header.</p>\n\n\n    function boo() {\n        targetText = document.getElementById("HiddenField1");\n        sourceText = document.getElementById("userbox");\n        targetText.value = escape(sourceText.innerText);\n    }\n</li>\n</ul>\n\n<p>In your textarea, include an onchange that calls boo():</p>\n\n<pre><code>&lt;textarea id="userbox"  onchange="boo();"&gt;&lt;/textarea&gt;\n</code></pre>\n\n<p>Finally, in .NET, use</p>\n\n<pre><code>string val = Server.UrlDecode(HiddenField1.Value);\n</code></pre>\n\n<p>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</p>\n\n<p>Here\'s an example I (MC9000) came up with and use via jQuery:</p>\n\n<pre><code>$(document).ready(function () {\n\n    $("#txtHTML").change(function () {\n        var currentText = $("#txtHTML").text();\n        currentText = escape(currentText); // Escapes the HTML including quotations, etc\n        $("#hidHTML").val(currentText); // Set the hidden field\n    });\n\n    // Intercept the postback\n    $("#btnMyPostbackButton").click(function () {\n        $("#txtHTML").val(""); // Clear the textarea before POSTing\n                               // If you don\'t clear it, it will give you\n                               // the error due to the HTML in the textarea.\n        return true; // Post back\n    });\n\n\n});\n</code></pre>\n\n<p>And the markup:</p>\n\n<pre><code>&lt;asp:HiddenField ID="hidHTML" runat="server" /&gt;\n&lt;textarea id="txtHTML"&gt;&lt;/textarea&gt;\n&lt;asp:Button ID="btnMyPostbackButton" runat="server" Text="Post Form" /&gt;\n</code></pre>\n\n<p>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 &amp; check for attacks before displaying elsewhere.</p>\n'}, {'answer_id': 29366891, 'author': 'Devendra Patel', 'author_id': 3027600, 'author_profile': 'https://Stackoverflow.com/users/3027600', 'pm_score': -1, 'selected': False, 'text': '<p>Try with </p>\n\n<blockquote>\n  <p><code>Server.Encode</code></p>\n</blockquote>\n\n<p>and </p>\n\n<blockquote>\n  <p><code>Server.HtmlDecode</code>\n    while sending and receiving.</p>\n</blockquote>\n'}, {'answer_id': 30838818, 'author': 'vakeel', 'author_id': 4222088, 'author_profile': 'https://Stackoverflow.com/users/4222088', 'pm_score': 4, 'selected': False, 'text': '<p><strong>Cause</strong></p>\n\n<p>ASP.NET by default validates all input controls for potentially unsafe contents that can lead to <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting</a> (XSS) and <a href="http://en.wikipedia.org/wiki/SQL_injection">SQL injections</a>. Thus it disallows such content by throwing the above exception. By default it is recommended to allow this check to happen on each postback.</p>\n\n<p><strong>Solution</strong></p>\n\n<p>On many occasions you need to submit HTML content to your page through Rich TextBoxes or Rich Text Editors. In that case you can avoid this exception by setting the ValidateRequest tag in the <code>@Page</code> directive to false.</p>\n\n<pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" ValidateRequest = "false" %&gt;\n</code></pre>\n\n<p>This will disable the validation of requests for the page you have set the ValidateRequest flag to false. If you want to disable this, check throughout your web application; you’ll need to set it to false in your web.config &lt;system.web> section</p>\n\n<pre><code>&lt;pages validateRequest ="false" /&gt;\n</code></pre>\n\n<p>For .NET 4.0 or higher frameworks you will need to also add the following line in the &lt;system.web> section to make the above work.</p>\n\n<pre><code>&lt;httpRuntime requestValidationMode = "2.0" /&gt;\n</code></pre>\n\n<p>That’s it. I hope this helps you in getting rid of the above issue.</p>\n\n<p>Reference by: <em><a href="http://www.aspsnippets.com/Articles/ASPNet-Error-A-potentially-dangerous-RequestForm-value-was-detected-from-the-client.aspx">ASP.Net Error: A potentially dangerous Request.Form value was detected from the client</a></em></p>\n'}, {'answer_id': 34196133, 'author': 'Durgesh Pandey', 'author_id': 5030579, 'author_profile': 'https://Stackoverflow.com/users/5030579', 'pm_score': 4, 'selected': False, 'text': '<p>If you\'re using framework 4.0 then the entry in the web.config (&lt;pages validateRequest="false" />)</p>\n\n<pre><code>&lt;configuration&gt;\n    &lt;system.web&gt;\n        &lt;pages validateRequest="false" /&gt;\n    &lt;/system.web&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>If you\'re using framework 4.5 then the entry in the web.config (requestValidationMode="2.0")</p>\n\n<pre><code>&lt;system.web&gt;\n    &lt;compilation debug="true" targetFramework="4.5" /&gt;\n    &lt;httpRuntime targetFramework="4.5" requestValidationMode="2.0"/&gt;\n&lt;/system.web&gt;\n</code></pre>\n\n<p>If you want for only single page then, In you aspx file you should put the first line as this :</p>\n\n<pre><code>&lt;%@ Page EnableEventValidation="false" %&gt;\n</code></pre>\n\n<p>if you already have something like  &lt;%@ Page so just add the rest => <code>EnableEventValidation="false"</code> %></p>\n\n<p>I recommend not to do it.</p>\n'}, {'answer_id': 35621783, 'author': 'Sel', 'author_id': 2706338, 'author_profile': 'https://Stackoverflow.com/users/2706338', 'pm_score': 2, 'selected': False, 'text': '<p>You can automatically HTML encode field in custom Model Binder. My solution some different, I put error in ModelState and display error message near the field. It`s easy to modify this code for automatically encode </p>\n\n<pre><code> public class AppModelBinder : DefaultModelBinder\n    {\n        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)\n        {\n            try\n            {\n                return base.CreateModel(controllerContext, bindingContext, modelType);\n            }\n            catch (HttpRequestValidationException e)\n            {\n                HandleHttpRequestValidationException(bindingContext, e);\n                return null; // Encode here\n            }\n        }\n        protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext,\n            PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)\n        {\n            try\n            {\n                return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);\n            }\n            catch (HttpRequestValidationException e)\n            {\n                HandleHttpRequestValidationException(bindingContext, e);\n                return null; // Encode here\n            }\n        }\n\n        protected void HandleHttpRequestValidationException(ModelBindingContext bindingContext, HttpRequestValidationException ex)\n        {\n            var valueProviderCollection = bindingContext.ValueProvider as ValueProviderCollection;\n            if (valueProviderCollection != null)\n            {\n                ValueProviderResult valueProviderResult = valueProviderCollection.GetValue(bindingContext.ModelName, skipValidation: true);\n                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);\n            }\n\n            string errorMessage = string.Format(CultureInfo.CurrentCulture, "{0} contains invalid symbols: &lt;, &amp;",\n                     bindingContext.ModelMetadata.DisplayName);\n\n            bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorMessage);\n        }\n    }\n</code></pre>\n\n<p>In Application_Start:</p>\n\n<pre><code>ModelBinders.Binders.DefaultBinder = new AppModelBinder();\n</code></pre>\n\n<p>Note that it works only for form fields. Dangerous value not passed to controller model, but stored in ModelState and can be redisplayed on form with error message. </p>\n\n<p>Dangerous chars in URL may be handled this way:</p>\n\n<pre><code>private void Application_Error(object sender, EventArgs e)\n{\n    Exception exception = Server.GetLastError();\n    HttpContext httpContext = HttpContext.Current;\n\n    HttpException httpException = exception as HttpException;\n    if (httpException != null)\n    {\n        RouteData routeData = new RouteData();\n        routeData.Values.Add("controller", "Error");\n        var httpCode = httpException.GetHttpCode();\n        switch (httpCode)\n        {\n            case (int)HttpStatusCode.BadRequest /* 400 */:\n                if (httpException.Message.Contains("Request.Path"))\n                {\n                    httpContext.Response.Clear();\n                    RequestContext requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);\n                    requestContext.RouteData.Values["action"] ="InvalidUrl";\n                    requestContext.RouteData.Values["controller"] ="Error";\n                    IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();\n                    IController controller = factory.CreateController(requestContext, "Error");\n                    controller.Execute(requestContext);\n                    httpContext.Server.ClearError();\n                    Response.StatusCode = (int)HttpStatusCode.BadRequest /* 400 */;\n                }\n                break;\n        }\n    }\n}\n</code></pre>\n\n<p>ErrorController:  </p>\n\n<pre><code>public class ErrorController : Controller\n {\n   public ActionResult InvalidUrl()\n   {\n      return View();\n   }\n}   \n</code></pre>\n'}, {'answer_id': 36721339, 'author': 'Voigt', 'author_id': 6166500, 'author_profile': 'https://Stackoverflow.com/users/6166500', 'pm_score': 1, 'selected': False, 'text': '<p>Use the <code>Server.HtmlEncode("yourtext");</code></p>\n'}, {'answer_id': 41679015, 'author': 'Peter', 'author_id': 58553, 'author_profile': 'https://Stackoverflow.com/users/58553', 'pm_score': 1, 'selected': False, 'text': '<p>For those of us still stuck on webforms I found the following solution that enables you to only disable the validation on one field! (I would hate to disable it for the whole page.)</p>\n\n<p>VB.NET:</p>\n\n<pre><code>Public Class UnvalidatedTextBox\n    Inherits TextBox\n    Protected Overrides Function LoadPostData(postDataKey As String, postCollection As NameValueCollection) As Boolean\n        Return MyBase.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form)\n    End Function\nEnd Class\n</code></pre>\n\n<p>C#:</p>\n\n<pre><code>public class UnvalidatedTextBox : TextBox\n{\n    protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)\n    {\n        return base.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form);\n    }\n}\n</code></pre>\n\n<p>Now just use <code>&lt;prefix:UnvalidatedTextBox id="test" runat="server" /&gt;</code> instead of <code>&lt;asp:TextBox</code>, and it should allow all characters (this is perfect for password fields!)</p>\n'}, {'answer_id': 48480067, 'author': 'dpant', 'author_id': 313935, 'author_profile': 'https://Stackoverflow.com/users/313935', 'pm_score': 1, 'selected': False, 'text': '<p>Last but not least, please note ASP.NET Data Binding controls automatically <strong>encode</strong> values during data binding. This changes the default behavior of all ASP.NET controls (TextBox, Label etc) contained in the <code>ItemTemplate</code>. The following sample demonstrates (<code>ValidateRequest</code> is set to false):</p>\n\n<p><strong>aspx</strong></p>\n\n<pre><code>&lt;%@ Page Language="C#" ValidateRequest="false" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication17._Default" %&gt; &lt;html&gt; &lt;body&gt;\n    &lt;form runat="server"&gt;\n        &lt;asp:FormView ID="FormView1" runat="server" ItemType="WebApplication17.S" SelectMethod="FormView1_GetItem"&gt;\n            &lt;ItemTemplate&gt;\n                &lt;asp:TextBox ID="TextBox1" runat="server"&gt;&lt;/asp:TextBox&gt;\n                &lt;asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /&gt;\n                &lt;asp:Label ID="Label1" runat="server" Text="&lt;%#: Item.Text %&gt;"&gt;&lt;/asp:Label&gt;\n                &lt;asp:TextBox ID="TextBox2" runat="server" Text="&lt;%#: Item.Text %&gt;"&gt;&lt;/asp:TextBox&gt;\n            &lt;/ItemTemplate&gt;\n        &lt;/asp:FormView&gt;\n    &lt;/form&gt; \n</code></pre>\n\n<p> \n</p>\n\n<p><strong>code behind</strong></p>\n\n<pre><code>public partial class _Default : Page\n{\n    S s = new S();\n\n    protected void Button1_Click(object sender, EventArgs e)\n    {\n        s.Text = ((TextBox)FormView1.FindControl("TextBox1")).Text;\n        FormView1.DataBind();\n    }\n\n    public S FormView1_GetItem(int? id)\n    {\n        return s;\n    }\n}\n\npublic class S\n{\n    public string Text { get; set; }\n}\n</code></pre>\n\n<ol>\n<li>Case submit value: <code>&amp;#39;</code></li>\n</ol>\n\n<p><code>Label1.Text</code> value: <code>&amp;#39;</code></p>\n\n<p><code>TextBox2.Text</code> value: <code>&amp;amp;#39;</code></p>\n\n<ol start="2">\n<li>Case submit value: <code>&lt;script&gt;alert(\'attack!\');&lt;/script&gt;</code></li>\n</ol>\n\n<p><code>Label1.Text</code> value: <code>&lt;script&gt;alert(\'attack!\');&lt;/script&gt;</code></p>\n\n<p><code>TextBox2.Text</code> value: <code>&amp;lt;script&amp;gt;alert(&amp;#39;attack!&amp;#39;);&amp;lt;/script&amp;gt;</code></p>\n'}, {'answer_id': 49307591, 'author': 'KiranC', 'author_id': 8167813, 'author_profile': 'https://Stackoverflow.com/users/8167813', 'pm_score': 0, 'selected': False, 'text': '<p>In .Net 4.0 and onwards, which is the usual case, put the following setting in system.web</p>\n\n<pre><code>&lt;system.web&gt;\n     &lt;httpRuntime requestValidationMode="2.0" /&gt;\n</code></pre>\n'}, {'answer_id': 49575929, 'author': 'Chris Catignani', 'author_id': 3072350, 'author_profile': 'https://Stackoverflow.com/users/3072350', 'pm_score': 2, 'selected': False, 'text': '<p>I see there\'s a lot written about this...and I didn\'t see this mentioned.\nThis has been available since .NET Framework 4.5</p>\n<p>The <a href="https://msdn.microsoft.com/en-us/library/system.web.ui.control.validaterequestmode.aspx" rel="nofollow noreferrer">ValidateRequestMode</a> setting for a control is a great option.\nThis way the other controls on the page are still protected.\nNo web.config changes needed.</p>\n<pre><code> protected void Page_Load(object sender, EventArgs e)\n {\n     txtMachKey.ValidateRequestMode = ValidateRequestMode.Disabled;\n }\n</code></pre>\n'}, {'answer_id': 49639591, 'author': 'Magnus', 'author_id': 1765710, 'author_profile': 'https://Stackoverflow.com/users/1765710', 'pm_score': 2, 'selected': False, 'text': '<p><strong>A solution</strong></p>\n\n<p>I don\'t like to turn off the post validation (validateRequest="false"). On the other hand it is not acceptable that the application crashes just because an innocent user happens to type <code>&lt;x</code> or something. </p>\n\n<p>Therefore I wrote a client side javascript function (xssCheckValidates) that makes a preliminary check. This function is called when there is an attempt to post the form data, like this:</p>\n\n<pre><code>&lt;form id="form1" runat="server" onsubmit="return xssCheckValidates();"&gt;\n</code></pre>\n\n<p>The function is quite simple and could be improved but it is doing its job.</p>\n\n<p>Please notice that the purpose of this is not to protect the system from hacking, it is meant to protect the users from a bad experience. The request validation done at the server is still turned on, and that is (part of) the protection of the system (to the extent it is capable of doing that). </p>\n\n<p>The reason i say "part of" here is because I have heard that the built in request validation might not be enough, so other complementary means might be necessary to have full protection. But, again, the javascript function I present here has <em>nothing</em> to do with protecting the system. It is <em>only</em> meant to make sure the users will not have a bad experience.</p>\n\n<p>You can try it out here:</p>\n\n<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>    function xssCheckValidates() {\r\n      var valid = true;\r\n      var inp = document.querySelectorAll(\r\n          "input:not(:disabled):not([readonly]):not([type=hidden])" +\r\n          ",textarea:not(:disabled):not([readonly])");\r\n      for (var i = 0; i &lt; inp.length; i++) {\r\n        if (!inp[i].readOnly) {\r\n          if (inp[i].value.indexOf(\'&lt;\') &gt; -1) {\r\n            valid = false;\r\n            break;\r\n          }\r\n          if (inp[i].value.indexOf(\'&amp;#\') &gt; -1) {\r\n            valid = false;\r\n            break;\r\n          }\r\n        }\r\n      }\r\n      if (valid) {\r\n        return true;\r\n      } else {\r\n        alert(\'In one or more of the text fields, you have typed\\r\\nthe character "&lt;" or the character sequence "&amp;#".\\r\\n\\r\\nThis is unfortunately not allowed since\\r\\nit can be used in hacking attempts.\\r\\n\\r\\nPlease edit the field and try again.\');\r\n        return false;\r\n      }\r\n    }</code></pre>\r\n<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form onsubmit="return xssCheckValidates();" &gt;\r\n  Try to type &lt; or &amp;# &lt;br/&gt;\r\n  &lt;input type="text" /&gt;&lt;br/&gt;\r\n  &lt;textarea&gt;&lt;/textarea&gt;\r\n  &lt;input type="submit" value="Send" /&gt;\r\n&lt;/form&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n'}, {'answer_id': 50174136, 'author': 'figolu', 'author_id': 3160060, 'author_profile': 'https://Stackoverflow.com/users/3160060', 'pm_score': 2, 'selected': False, 'text': '<p>I know this question is about form posting, but I would like to add some details for people who received this error on others circumstances. It could also occur on a handler used to implement a web service.  </p>\n\n<p>Suppose your web client sends POST or PUT requests using ajax and sends either json or xml text or raw data (a file content) to your web service. Because your web service does not need to get any information from a Content-Type header, your JavaScript code did not set this header to your ajax request. But if you do not set this header on a POST/PUT ajax request, Safari may add this header: "Content-Type: application/x-www-form-urlencoded". I observed that on Safari 6 on iPhone, but others Safari versions/OS or Chrome may do the same. So when receiving this Content-Type header some part of .NET Framework assume the request body data structure corresponds to an html form posting while it does not and rose an HttpRequestValidationException exception. First thing to do is obviously to always set Content-Type header to anything but a form MIME type on a POST/PUT ajax request even it is useless to your web service.</p>\n\n<p>I also discovered this detail:<br>\nOn these circumstances, the HttpRequestValidationException exception is rose when your code tries to access HttpRequest.Params collection. But surprisingly, this exception is not rose when it accesses HttpRequest.ServerVariables collection. This shows that while these two collections seem to be nearly identical, one accesses request data through security checks and the other one does not.</p>\n'}, {'answer_id': 51490934, 'author': 'Wahid Masud', 'author_id': 5538471, 'author_profile': 'https://Stackoverflow.com/users/5538471', 'pm_score': 3, 'selected': False, 'text': '<p>For those who are not using model binding, who are extracting each parameter from the Request.Form, who are sure the input text will cause no harm, there is another way. Not a great solution but it will do the job.  </p>\n\n<p>From client side, encode it as uri then send it.<br>\ne.g:  </p>\n\n<pre><code>encodeURIComponent($("#MsgBody").val());  \n</code></pre>\n\n<p>From server side, accept it and decode it as uri.<br>\ne.g:  </p>\n\n<pre><code>string temp = !string.IsNullOrEmpty(HttpContext.Current.Request.Form["MsgBody"]) ?\nSystem.Web.HttpUtility.UrlDecode(HttpContext.Current.Request.Form["MsgBody"]) : \nnull;  \n</code></pre>\n\n<p>or  </p>\n\n<pre><code>string temp = !string.IsNullOrEmpty(HttpContext.Current.Request.Form["MsgBody"]) ?\nSystem.Uri.UnescapeDataString(HttpContext.Current.Request.Form["MsgBody"]) : \nnull; \n</code></pre>\n\n<p>please look for the differences between <code>UrlDecode</code> and <code>UnescapeDataString</code></p>\n'}, {'answer_id': 53590303, 'author': 'maozx', 'author_id': 1516208, 'author_profile': 'https://Stackoverflow.com/users/1516208', 'pm_score': 3, 'selected': False, 'text': '<p>in my case, using asp:Textbox control (Asp.net 4.5), instead of setting the all page for <code>validateRequest="false"</code> \ni used </p>\n\n<pre><code>&lt;asp:TextBox runat="server" ID="mainTextBox"\n            ValidateRequestMode="Disabled"\n &gt;&lt;/asp:TextBox&gt;\n</code></pre>\n\n<p>on the Textbox that caused the exception.</p>\n'}, {'answer_id': 61640372, 'author': 'Sanjeev Singh', 'author_id': 3288863, 'author_profile': 'https://Stackoverflow.com/users/3288863', 'pm_score': 0, 'selected': False, 'text': '<p><strong>How to fix this issue for AjaxExtControls in ASP.NET 4.6.2:</strong></p>\n\n<p>We had the same problem with AjaxExtControls rich text editor. This issue started right after upgrading from .NET 2.0 to .NET 4.5. I looked at all SOF answers but could not find a solution that does not compromise with the security provided by .NET 4.5.</p>\n\n<p><strong>Fix 1(Not Recommended as it can degrade application security)</strong> : I tested after changing this attribute in \n<code>requestValidationMode = "2.0</code> and it worked but I was concerned about the security features. So this is fix is like degrading the security for entire application.</p>\n\n<p><strong>Fix 2 (Recommended):</strong> Since this issue was only occurring with one of AjaxExtControl, I was finally able to solve this issue using the simple code below:</p>\n\n<pre><code>editorID.value = editorID.value.replace(/&gt;/g, "&amp;gt;");\neditorID.value = editorID.value.replace(/&lt;/g, "&amp;lt;");\n</code></pre>\n\n<p>This code is executed on client side (javascript) before sending the request to server. Note that the editorID is not the ID that we have on our html/aspx pages but it is the id of the rich text editor that AjaxExtControl internally uses.</p>\n'}, {'answer_id': 67008025, 'author': 'syntap', 'author_id': 2108172, 'author_profile': 'https://Stackoverflow.com/users/2108172', 'pm_score': 0, 'selected': False, 'text': '<p>I have a Web Forms application that has had this issue for a text box comments field, where users sometimes pasted email text, and the &quot;&lt;&quot; and &quot;&gt;&quot; characters from email header info would creep in there and throw this exception.</p>\n<p>I addressed the issue from another angle... I was already using Ajax Control Toolkit, so I was able to use a FilteredTextBoxExtender to prevent those two characters from entry in the text box.  A user copy-pasting text will then get what they were expecting, minus those characters.</p>\n<pre><code>&lt;asp:TextBox ID=&quot;CommentsTextBox&quot; runat=&quot;server&quot; TextMode=&quot;MultiLine&quot;&gt;&lt;/asp:TextBox&gt;\n&lt;ajaxToolkit:FilteredTextBoxExtender ID=&quot;ftbe&quot; runat=&quot;server&quot; TargetControlID=&quot;CommentsTextBox&quot; filterMode=&quot;InvalidChars&quot; InvalidChars=&quot;&lt;&gt;&quot; /&gt;\n</code></pre>\n'}, {'answer_id': 70332576, 'author': 'Colin', 'author_id': 150342, 'author_profile': 'https://Stackoverflow.com/users/150342', 'pm_score': 0, 'selected': False, 'text': "<p>None of the answers worked for me. Then I discovered that if I removed the following code I could get it to work:</p>\n<pre><code>//Register action filter via Autofac rather than GlobalFilters to allow dependency injection\nbuilder.RegisterFilterProvider();\nbuilder.RegisterType&lt;OfflineActionFilter&gt;()\n    .AsActionFilterFor&lt;Controller&gt;()\n    .InstancePerLifetimeScope();\n</code></pre>\n<p>I can only conclude that something in Autofac's RegisterFilterProvider breaks or overrides the validateRequest attribute</p>\n"}, {'answer_id': 70866955, 'author': 'jcs', 'author_id': 2526059, 'author_profile': 'https://Stackoverflow.com/users/2526059', 'pm_score': 0, 'selected': False, 'text': '<p>Even after adding <code>&lt;httpRuntime requestValidationMode=&quot;2.0&quot;&gt;</code> to web.config I still kept getting the error in an application that uses WIF for authentication.<br>\nWhat solved for me was adding <code>&lt;sessionState mode=&quot;InProc&quot; cookieless=&quot;UseUri&quot;/&gt;</code> inside the <code>&lt;system.web&gt;</code> element.</p>\n'}]
['https://Stackoverflow.com/questions/81991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3263/']