This is a common error that ASP.NET developers have run into many times. We will see in this article a few ways on how to avoid it, both in Web Forms and MVC.
This error occurs mostly because the data that are sent in the web server contain HTML. By default there a validation check on all input so that our web application has a basic protection from XSS attacks.
The easy way is to disable this validation process. This can be done by setting the below properties in the Web.config file.
<configuration> <system.web> <pages validateRequest="false" /> </system.web> </configuration>
In .NET 4.0, you need to change one more property.
<configuration> <system.web> <pages validateRequest="false" /> <httpRuntime requestValidationMode="2.0"/> </system.web> </configuration>
If you want to apply this setting to a specific page, you can set it in the page directive of your .aspx file.
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Example.aspx.cs" Inherits="Example.Example" ValidateRequest="false" %>
In case your web application is an ASP.NET MVC project and want to disable page validation for a specific view, you can set this property to its controller.
[Post, ValidateInput(false)] public ActionResult Edit(...) { ... }
In MVC, you can actually declare which properties of your model you want to exclude from the validation process.
[HttpPost, ValidateInput(true, Exclude = "YourFieldName")] public virtual ActionResult Edit(...) { ... }
Another approach is to set at the property of the Model to allow HTML content.
[AllowHtml] public string Description { get; set; }
Going back to Web Forms, if you want to allow HTML / JavaScript for a specific field, there is no direct way to do it. A nice trick you could do, is to encode the HTML in the client side and then decode it in the server side.
The client side code
// The event to escape the data and store in our HiddenField jQuery('.allow_html textarea').blur(function () { jQuery(jQuery(this).parent()).find('input[type="hidden"]').val(escape(jQuery(this).val())); }); // The code to unescape the code and set it in our textbox jQuery('.allow_html textarea').each(function(idx, item) { var value = jQuery(jQuery(item).parent()).find('input[type="hidden"]').val(); jQuery(item).val(unescape(value)); });
The server side code
// encode the data HtmlCodeHiddenField.Value = Uri.EscapeDataString(EscapedHtml); // decode the data string myHtml = Uri.UnescapeDataString(HtmlCodeHiddenField.Value);
If you want to read more about this subject, read this article from Stack Overflow.
From another side setting pages validateRequest=”false” opens your web page to Cross Site Injection (XSS) attacks. Use Server.HtmlEncode or some AntiXSS libarary functions
Good. I prefer to just escape and unescape on client side
I got the error when a user had a password containing an ampersand and a pound sign side-by-side. But that’s not HTML.