1577

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 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.

Trapping the exception and showing

An error has occurred please go back and re-type your entire form again, but this time please do not use <

doesn't seem professional enough to me.

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

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

Is there a way I can do this from a handler?

6
  • 76
    Note that you can get this error if you have HTML entity names (&amp;) or entity numbers (&#39;) in your input too. Oct 14, 2010 at 2:50
  • 31
    Well, since it's my question I feel I can define what the point actually is: crashing an entire application process and returning a generic error message because somebody typed a '<' is overkill. Especially since you know most people will just 'validateRequest=false' to get rid of it, thus re-opening the vulnerability
    – Radu094
    Sep 18, 2014 at 17:23
  • 10
    @DrewNoakes: entity names (&amp;) do not seem to be a problem according to my tests (tested in .Net 4.0), although entity numbers (&#39;) do fail validation (as you said). If you disassemble the System.Web.CrossSiteScriptingValidation.IsDangerousString method using .Net Reflector, you'll see that the code looks specifically for html tags (starting with <) and entity numbers (starting with &#)
    – Gyum Fox
    May 6, 2015 at 15:52
  • 9
    Create a new site in VS2014 using the default MVC project and run it. Click the register link, add any email, and use "<P455-0r[!" as the password. Same error out of the box, not trying to do anything malicious, the password field won't be displayed so it won't be a XSS attack, but the only way to fix it is to completely remove validation with the ValidateInput(false)? The AllowHtml suggestion doesn't work in this situation, still blew up with the same error. A potentially dangerous Request.Form value was detected from the client (Password="<P455-0r[!"). May 26, 2015 at 22:34
  • TL;DR put <httpRuntime requestValidationMode="2.0" /> in web.config
    – user3638471
    Nov 2, 2016 at 19:15

47 Answers 47

1
2
5

in my case, using asp:Textbox control (Asp.net 4.5), instead of setting the all page for validateRequest="false" i used

<asp:TextBox runat="server" ID="mainTextBox"
            ValidateRequestMode="Disabled"
 ></asp:TextBox>

on the Textbox that caused the exception.

0
5

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.

From client side, encode it as uri then send it.
e.g:

encodeURIComponent($("#MsgBody").val());  

From server side, accept it and decode it as uri.
e.g:

string temp = !string.IsNullOrEmpty(HttpContext.Current.Request.Form["MsgBody"]) ?
System.Web.HttpUtility.UrlDecode(HttpContext.Current.Request.Form["MsgBody"]) : 
null;  

or

string temp = !string.IsNullOrEmpty(HttpContext.Current.Request.Form["MsgBody"]) ?
System.Uri.UnescapeDataString(HttpContext.Current.Request.Form["MsgBody"]) : 
null; 

please look for the differences between UrlDecode and UnescapeDataString

0
4

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.

0
4

As indicated in my comment to Sel's answer, this is our extension to a custom request validator.

public class SkippableRequestValidator : RequestValidator
{
    protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
    {
        if (collectionKey != null && collectionKey.EndsWith("_NoValidation"))
        {
            validationFailureIndex = 0;
            return true;
        }

        return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
    }
}
0
3

You should use the Server.HtmlEncode method to protect your site from dangerous input.

More info here

2
  • 3
    Use the Anti-XSS Library to prevent this error... this is incomplete. Oct 21, 2011 at 22:51
  • Giving a little more explanation on how to do this might be helpfull. Mar 6, 2019 at 8:38
3

A solution

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 <x or something.

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:

<form id="form1" runat="server" onsubmit="return xssCheckValidates();">

The function is quite simple and could be improved but it is doing its job.

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).

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 nothing to do with protecting the system. It is only meant to make sure the users will not have a bad experience.

You can try it out here:

    function xssCheckValidates() {
      var valid = true;
      var inp = document.querySelectorAll(
          "input:not(:disabled):not([readonly]):not([type=hidden])" +
          ",textarea:not(:disabled):not([readonly])");
      for (var i = 0; i < inp.length; i++) {
        if (!inp[i].readOnly) {
          if (inp[i].value.indexOf('<') > -1) {
            valid = false;
            break;
          }
          if (inp[i].value.indexOf('&#') > -1) {
            valid = false;
            break;
          }
        }
      }
      if (valid) {
        return true;
      } else {
        alert('In one or more of the text fields, you have typed\r\nthe character "<" or the character sequence "&#".\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.');
        return false;
      }
    }
<form onsubmit="return xssCheckValidates();" >
  Try to type < or &# <br/>
  <input type="text" /><br/>
  <textarea></textarea>
  <input type="submit" value="Send" />
</form>

2
  • You should assume any code that runs on the client will be subverted.
    – user169771
    Apr 5, 2018 at 14:55
  • 2
    @user169771, read my answer again, especially the part that starts with "Please notice that the purpose of this is not to protect the system from hacking..."
    – Magnus
    Apr 5, 2018 at 15:57
2

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.

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.

I also discovered this detail:
On 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.

2

I see there's a lot written about this...and I didn't see this mentioned. This has been available since .NET Framework 4.5

The ValidateRequestMode setting for a control is a great option. This way the other controls on the page are still protected. No web.config changes needed.

 protected void Page_Load(object sender, EventArgs e)
 {
     txtMachKey.ValidateRequestMode = ValidateRequestMode.Disabled;
 }
1
  • 1
    @PruTahan....and you needed to comment on every post because? The OP error message is cause by any one of a number of different reasons. Jan 9, 2019 at 13:53
1

Use the Server.HtmlEncode("yourtext");

0
1

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.)

VB.NET:

Public Class UnvalidatedTextBox
    Inherits TextBox
    Protected Overrides Function LoadPostData(postDataKey As String, postCollection As NameValueCollection) As Boolean
        Return MyBase.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form)
    End Function
End Class

C#:

public class UnvalidatedTextBox : TextBox
{
    protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
    {
        return base.LoadPostData(postDataKey, System.Web.HttpContext.Current.Request.Unvalidated.Form);
    }
}

Now just use <prefix:UnvalidatedTextBox id="test" runat="server" /> instead of <asp:TextBox, and it should allow all characters (this is perfect for password fields!)

0
1

Last but not least, please note ASP.NET Data Binding controls automatically encode values during data binding. This changes the default behavior of all ASP.NET controls (TextBox, Label etc) contained in the ItemTemplate. The following sample demonstrates (ValidateRequest is set to false):

aspx

<%@ Page Language="C#" ValidateRequest="false" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication17._Default" %> <html> <body>
    <form runat="server">
        <asp:FormView ID="FormView1" runat="server" ItemType="WebApplication17.S" SelectMethod="FormView1_GetItem">
            <ItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
                <asp:Label ID="Label1" runat="server" Text="<%#: Item.Text %>"></asp:Label>
                <asp:TextBox ID="TextBox2" runat="server" Text="<%#: Item.Text %>"></asp:TextBox>
            </ItemTemplate>
        </asp:FormView>
    </form> 

code behind

public partial class _Default : Page
{
    S s = new S();

    protected void Button1_Click(object sender, EventArgs e)
    {
        s.Text = ((TextBox)FormView1.FindControl("TextBox1")).Text;
        FormView1.DataBind();
    }

    public S FormView1_GetItem(int? id)
    {
        return s;
    }
}

public class S
{
    public string Text { get; set; }
}
  1. Case submit value: &#39;

Label1.Text value: &#39;

TextBox2.Text value: &amp;#39;

  1. Case submit value: <script>alert('attack!');</script>

Label1.Text value: <script>alert('attack!');</script>

TextBox2.Text value: &lt;script&gt;alert(&#39;attack!&#39;);&lt;/script&gt;

0
0

In .Net 4.0 and onwards, which is the usual case, put the following setting in system.web

<system.web>
     <httpRuntime requestValidationMode="2.0" />
0

How to fix this issue for AjaxExtControls in ASP.NET 4.6.2:

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.

Fix 1(Not Recommended as it can degrade application security) : I tested after changing this attribute in requestValidationMode = "2.0 and it worked but I was concerned about the security features. So this is fix is like degrading the security for entire application.

Fix 2 (Recommended): Since this issue was only occurring with one of AjaxExtControl, I was finally able to solve this issue using the simple code below:

editorID.value = editorID.value.replace(/>/g, "&gt;");
editorID.value = editorID.value.replace(/</g, "&lt;");

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.

0

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 "<" and ">" characters from email header info would creep in there and throw this exception.

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.

<asp:TextBox ID="CommentsTextBox" runat="server" TextMode="MultiLine"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="ftbe" runat="server" TargetControlID="CommentsTextBox" filterMode="InvalidChars" InvalidChars="<>" />
0

None of the answers worked for me. Then I discovered that if I removed the following code I could get it to work:

//Register action filter via Autofac rather than GlobalFilters to allow dependency injection
builder.RegisterFilterProvider();
builder.RegisterType<OfflineActionFilter>()
    .AsActionFilterFor<Controller>()
    .InstancePerLifetimeScope();

I can only conclude that something in Autofac's RegisterFilterProvider breaks or overrides the validateRequest attribute

0

Even after adding <httpRuntime requestValidationMode="2.0"> to web.config I still kept getting the error in an application that uses WIF for authentication.
What solved for me was adding <sessionState mode="InProc" cookieless="UseUri"/> inside the <system.web> element.

-1

Try with

Server.Encode

and

Server.HtmlDecode while sending and receiving.

1
  • 1
    You can't even get that far (that is you can't post back, so nothing you do on the code-behind will work) with validation on - the point of the user's question.
    – MC9000
    Jun 13, 2015 at 7:47
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.