1516

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?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Radu094
  • 26,658
  • 16
  • 56
  • 77
  • 70
    Note that you can get this error if you have HTML entity names (&) or entity numbers (') in your input too. – Drew Noakes Oct 14 '10 at 02:50
  • 22
    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 ' – Radu094 Sep 18 '14 at 17:23
  • 7
    @DrewNoakes: entity names (&) do not seem to be a problem according to my tests (tested in .Net 4.0), although entity numbers (') 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 – Gyum Fox May 06 '15 at 15:52
  • 7
    Create a new site in VS2014 using the default MVC project and run it. Click the register link, add any email, and use " – stephenbayer May 26 '15 at 22:34
  • TL;DR put `` in web.config –  Nov 02 '16 at 19:15
  • See also [ASP.NET 4 Breaking Changes](https://docs.microsoft.com/en-us/aspnet/whitepapers/aspnet4/breaking-changes#aspnet-request-validation) for some background. – Bouke Nov 06 '18 at 08:08

45 Answers45

1112

I think you are attacking it from the wrong angle by trying to encode all posted data.

Note that a "<" could also come from other outside sources, like a database field, a configuration, a file, a feed and so on.

Furthermore, "<" 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).

In other contexts different sub-strings are dangerous, for example, if you write an user-provided URL into a link, the sub-string "javascript:" 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.

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

When you are sure you HTML-encode everywhere you pass strings to HTML, then set ValidateRequest="false" in the <%@ Page ... %> directive in your .aspx file(s).

In .NET 4 you may need to do a little more. Sometimes it's necessary to also add <httpRuntime requestValidationMode="2.0" /> to web.config (reference).

Satinder singh
  • 9,340
  • 15
  • 53
  • 93
JacquesB
  • 39,558
  • 12
  • 64
  • 79
  • @Hightechrider thanks for that link. Simple setting validateRequest="false" doesn't work for a view in ASP.Net MVC @olavk - Nice. Joel took the time to comment on your answer. – IEnumerator Apr 27 '10 at 15:21
  • 76
    To those coming in late: validateRequest="false" goes in the Page directive (first line of your .aspx file) – MGOwen Oct 20 '10 at 05:28
  • 59
    Tip: Put `` in a location tag to avoid killing the useful protection provided by validation from the rest of your site. – Brian May 17 '11 at 14:05
  • Looks like works only when 2.0 framework is installed on the machine. What if 2.0 framework is not installed at all but only 4.0 framework is installed? – Samuel Jul 20 '11 at 18:17
  • 308
    In MVC3, this is `[AllowHtml]` on the model property. – Jeremy Holovacs Sep 09 '11 at 19:30
  • 4
    To disable it globally for MVC 3 you also need `GlobalFilters.Filters.Add(new ValidateInputAttribute(false));` in `Application_Start()`. – Alex Jul 18 '12 at 11:14
  • 16
    @MGOwen you can also add the page directive to the web.config via `` in ``. Doing so will apply the property to all pages. – m-smith Jul 31 '12 at 09:56
  • 2
    [This answer](http://stackoverflow.com/a/4269513/3429) to [this question](http://stackoverflow.com/questions/2673850/validaterequest-false-doesnt-work-in-asp-net-4) has a reference to setting the requestValidationMode="2.0" for only a single page on your site, which is definitely more secure than turning the validation off for an entire site. – Steve Wranovsky Aug 08 '12 at 20:07
  • You can use `CausesValidation="false"` on specific controls in WebForms. – Justin Skiles Oct 24 '13 at 15:15
  • 1
    I would like to point out that not only "javascript:" can be dangerous. Imagine what would "" do to your layout. – Vojtech B May 24 '14 at 15:44
  • Is there any method other than disabling validateRequest, since it threatens the security of the web site. – NCA Jun 30 '14 at 06:38
  • I just want to point out that dynamic SQL running on SQL Server should always be executed using sp_executesql to reduce security risk. – devinbost Aug 29 '14 at 08:36
  • @Samuel: `requestValidationMode="4.0"` (or anything >= 4.0) means that the validation is done whenever a HTTP request data is accessed (url, cookies). `requestValidationMode="2.0"` (or anything less than 4.0) is to enable HTTP request validation for pages only. Take a look at the MSDN: http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.requestvalidationmode(v=vs.100).aspx – Dio Phung Sep 30 '14 at 03:01
  • @AdamKDean [ValidateInput(false)] only works if the offending characters are in the query string. If they're in the request path, this doesn't work – PandaWood Mar 24 '16 at 02:25
  • 2
    In ASP.NET MVC, Razor has automatically HTML-encoded strings since 2010. So I think one can use `[ValidateInput(false)]` on one's POST controller actions (that receive form data) safely? – nmit026 Dec 11 '16 at 21:25
  • @JustinSkiles `CausesValidation` only changes so the field does not trigger validation of field validators like `RequiredFieldValidator`. – Peter Jan 16 '17 at 14:22
  • for .net 4 requestvalidationmode is needed inside web.config too – masoud Cheragee Apr 03 '17 at 08:26
  • 1
    why this issue not occuring in local host,but only occurs on server just curious to know..however your solution of adding validate request=false worked fine for me – clarifier Jul 06 '17 at 09:17
  • How to set location path for whole site/domain? (dot is not working) – PPB May 04 '18 at 07:00
  • @clarifier it appears that IIS Express defaults to `requestValidationMode="2.0"` instead of `"4.5"` on IIS. Specifying either `2.0` or `4.5` gives the same behaviour in your local environment (assuming IIS Express) as well as on production. – Bouke Nov 06 '18 at 08:09
  • @JacquesB Hey, might want to edit it slightly just to make the Server.HtmlEncode stand out a little more. I think this is what people are looking for most of the time as it's the actual implementation, yet I know I've skipped over reading it too many times. – DubDub Apr 29 '19 at 11:03
  • Needed ``` ``` And `````` in the web.config for this to workout. Thanks OP @JacquesB – mlaribi Mar 16 '20 at 06:16
  • In .NET 4 in web.config add: – mirko cro 1234 Sep 17 '20 at 07:38
  • This worked for me – A X Jan 09 '21 at 19:29
514

There's a different solution to this error if you're using ASP.NET MVC:

C# sample:

[HttpPost, ValidateInput(false)]
public ActionResult Edit(FormCollection collection)
{
    // ...
}

Visual Basic sample:

<AcceptVerbs(HttpVerbs.Post), ValidateInput(False)> _
Function Edit(ByVal collection As FormCollection) As ActionResult
    ...
End Function
Ra.
  • 2,299
  • 3
  • 26
  • 38
Zack Peterson
  • 53,106
  • 76
  • 203
  • 279
  • the problem may be come when it's need on one page of whole application –  Dec 18 '10 at 06:03
  • 3
    You can also add the [ValidateInput(false)] attribute at the class level. If you add it to your base controller class, it will apply to all controller method actions. – Shan Plourde May 29 '11 at 13:12
  • @Zack Thanks for the solution. On the other hand I am wondering if `[AllowHtml]` is better than `ValidateInput(false)`, because `[AllowHtml]`is defined at once for a property i.e. Editor field and whenever it is used there is no need to use it for several actions. What do you suggest? – Jack Jul 21 '15 at 23:44
  • @Zack Peterson Is it safe to use? No security issue? – shrey Pav Oct 30 '17 at 07:21
431

In ASP.NET MVC (starting in version 3), you can add the AllowHtml attribute to a property on your model.

It allows a request to include HTML markup during model binding by skipping request validation for the property.

[AllowHtml]
public string Description { get; set; }
Marius
  • 54,363
  • 28
  • 121
  • 143
Anthony Johnston
  • 8,972
  • 4
  • 39
  • 54
  • 13
    Much better to do this declarativly than in the controller! – Andiih Mar 09 '12 at 09:03
  • Did this disappear in MVC 4? – granadaCoder Jul 24 '15 at 15:08
  • It seems to only be in DotNet 4.0 Framework. https://msdn.microsoft.com/en-us/library/system.web.mvc%28v=vs.100%29.aspx Do What??? – granadaCoder Jul 24 '15 at 15:10
  • thanks dude...your are great...i really appreciate this answer..thanks...thanks..2 hour wasted in finding y i get this error – Rakeshyadvanshi Jan 18 '16 at 05:55
  • 1
    What is the difference between `ValidateInput(false)` and `AllowHtml`? What is the advantage of one over the other? When would i want to use `AllowHtml` instead of `ValidateInput(false)`? When would i want to use `ValidateInput(false)` over `AllowHtml`? When would i want to use both? Does it make sense to use both? – Ian Boyd Jul 29 '16 at 13:55
  • 3
    ValidateInput is on the method, AllowHtml is on the property of the model - so you only allow the one you expect to have html - not all – Anthony Johnston Aug 10 '16 at 15:07
  • I've used [AllowHtml] but I find myself in a position where I don't have a model since the form contains a dynamic set of properties, based on data-driven configuration. The model binding isn't smart enough to put those "back" into the lists, so I parse them from Request.Form. Is there anyway to do it for just one field on Request.Form, or am I perhaps missing something with how to handle this use case within MVC? – Julia McGuigan Jun 06 '18 at 15:55
  • To use [AllowHtml]. Please add "using System.Web.Mvc;" This helped me stay secure as well as escaping the only field where I expected to receive dangerous unencoded html. Pro tip: "using System.Web;" //Before saving to the database please be sure to run an html encoder like this "string myEncodedString = HttpUtility.HtmlEncode(myString);" //While retrieving from the db you can similarly run a decoder like this "StringWriter myWriter = new StringWriter();" // Decode the encoded string like this. "HttpUtility.HtmlDecode(myEncodedString, myWriter);" – Paras Parmar Jun 05 '20 at 15:47
216

If you are on .NET 4.0 make sure you add this in your web.config file inside the <system.web> tags:

<httpRuntime requestValidationMode="2.0" />

In .NET 2.0, request validation only applied to aspx requests. In .NET 4.0 this was expanded to include all requests. You can revert to only performing XSS validation when processing .aspx by specifying:

requestValidationMode="2.0"

You can disable request validate entirely by specifying:

validateRequest="false"
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
JordanC
  • 4,220
  • 1
  • 20
  • 15
  • 31
    Inside the `` tags. – Hosam Aly Nov 04 '10 at 11:26
  • 8
    I've put this in the web.config, but still to the error "A potentially dangerous Request.Form value " – Filip Dec 12 '10 at 15:40
  • 20
    Looks like works only when 2.0 framework is installed on the machine. What if 2.0 framework is not installed at all but only 4.0 framework is installed? – Samuel Jul 20 '11 at 18:18
  • This totally worked for me. None of the steps document in the other answers were necessary (including validateRequest="false")! – tom redfern Oct 02 '12 at 10:53
116

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 <location> element. This will make sure all your other pages are safe. You do NOT need to put ValidateRequest="false" in your .aspx page.

<configuration>
...
  <location path="MyFolder/.aspx">
    <system.web>
      <pages validateRequest="false" />
      <httpRuntime requestValidationMode="2.0" />
    </system.web>
  </location>
...
</configuration>

It is safer to control this inside your web.config, because you can see at a site level which pages allow markup as input.

You still need to programmatically validate input on pages where request validation is disabled.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Carter Medlin
  • 10,482
  • 4
  • 55
  • 65
  • More info on requestValidationMode=2|4 here: https://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.requestvalidationmode%28v=vs.110%29.aspx – GlennG Feb 13 '15 at 08:30
  • Sadly this won't work with ASP.net 2.0 as is. Remove the httpRuntime line and it will work. – Fandango68 Mar 11 '15 at 05:48
  • I added a warning reminding people to manually validate input when validation is disabled. – Carter Medlin Jun 17 '15 at 00:35
73

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:

[HttpPost, ValidateInput(true, Exclude = "YourFieldName")]
public virtual ActionResult Edit(int id, FormCollection collection)
{
    ...
}

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.

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
gligoran
  • 3,019
  • 3
  • 28
  • 42
  • 10
    Sadly it looks like the Exclude feature was removed from MVC 3 RTW :( – Matt Greer Mar 23 '11 at 16:18
  • 3
    Nor was it included in MVC 4 – wilsjd Jun 27 '13 at 19:41
  • 9
    Use `[AllowHtml]` on the model's properties instead of `[ValidateInput]` on the Action to achieve the same end result. – Mrchief Mar 25 '14 at 17:07
  • @gligoran Is `[AllowHtml]` better than `ValidateInput(false)` for Editor fields? Because `[AllowHtml]`is defined at once for a property i.e. Editor field and whenever it is used there is no need to use it for several actions. What do you suggest? – Jack Jul 21 '15 at 23:46
  • 2
    @Christof Note that my answer is 5 years old. I haven't come across this problem in a really long while, so there might be a lot better ways of dealing with it. Regarding this two options I think it depends on your situation. Maybe you expose that model in more than one actions and in some places HTML is allowed or not. In such a case ```[AllowHtml]``` isn't an options. I recommend checking out this article: http://weblogs.asp.net/imranbaloch/understanding-request-validation-in-asp-net-mvc-3, but it too is somewhat old and might be out of date. – gligoran Jul 22 '15 at 16:13
  • @gligoran Ok, thanks. I tried to use `[AllowHtml]` in MVC5, but see that `ValidateInput(false)` is better and has no problem. Thanks again for your reply. – Jack Jul 22 '15 at 19:52
  • 1
    There's still a a way to exclude particular method parameters from validation, check out my answer here: https://stackoverflow.com/a/50796666/56621 – Alex from Jitbit Nov 14 '18 at 22:07
53

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:

<httpRuntime requestValidationMode="2.0"/>

<configuration>
    <system.web>
        <pages validateRequest="false" />
    </system.web>
</configuration>

and

[Post, ValidateInput(false)]
public ActionResult Edit(string message) {
    ...
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
ranthonissen
  • 1,425
  • 15
  • 16
  • 2
    For me, `validateRequest="false"` was not necessary, only `requestValidationMode="2.0"` – tom redfern Oct 02 '12 at 10:54
  • requestValidationMode="2.0" still generates the error with HTMLencoded data. No solution except to base64 encode everything, then send it along. – MC9000 Jun 13 '15 at 07:35
48

You can HTML encode 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."

Kolappan N
  • 2,178
  • 2
  • 26
  • 31
Pavel Chuchuva
  • 21,289
  • 9
  • 93
  • 110
45

The answer to this question is simple:

var varname = Request.Unvalidated["parameter_name"];

This would disable validation for the particular request.

Jens Erat
  • 33,889
  • 16
  • 73
  • 90
flakomalo
  • 660
  • 5
  • 4
  • 1
    Only applicable for ASP.NET 4.5 (and, presumably, whatever will come after it.) Pre 4.5 does not support this. – Beska Nov 04 '14 at 20:00
  • 3
    I wish I could bump this way up. I'm using .NET 4.5 and this is exactly what I needed since I'm not using MVC and I cannot change the web.config. – Chris Gillum Nov 18 '14 at 19:26
  • 1
    Yeah but what if you're using .Net 2? Some of us have no choice – Fandango68 Mar 18 '15 at 04:12
  • this gets POST or GET parameters? – max4ever Apr 15 '15 at 09:58
  • Are you saying this prevents an exception that was already thrown? Or does .net 4.5 delay the exception and validation until data is actually read from the `Request`? – ebyrob Mar 08 '17 at 14:49
  • This was the only option I could use. I have to pull directly from the Request/Form, without using Models or Parameters in MVC. The other options still validated the input. – Jesse Sierks Oct 17 '17 at 19:26
43

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.

    void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();

        if (ex is HttpRequestValidationException)
        {
            Response.Clear();
            Response.StatusCode = 200;
            Response.Write(@"[html]");
            Response.End();
        }
    }

Redirecting to another page also seems like a reasonable response to the exception.

http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html

BenMaddox
  • 1,710
  • 3
  • 18
  • 28
43

For MVC, ignore input validation by adding

[ValidateInput(false)]

above each Action in the Controller.

A.Dara
  • 774
  • 8
  • 22
  • This doesn't seem to work in the case that it gets to the controller method via a configured route. – PandaWood Mar 24 '16 at 00:39
  • Actually, the technical explanation, is that this only works when the offending character is in the "query string"... if it's in the request path, Validation attribute *does not* work – PandaWood Mar 24 '16 at 02:08
35

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 < into &lt;, > into &gt; and & into &amp;. So be wary of doing this...

myTextBox.Text = Server.HtmlEncode(myStringFromDatabase); // Pseudo code

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 <script> window.location = "http://www.google.com"; </script> from being output into your page and subsequently executed.

Do a little experimenting to see what gets encoded and what doesn't.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
29

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.

Example:

<configuration>
  <system.web>
   <httpRuntime requestValidationMode="2.0" />
  </system.web>
  <pages validateRequest="false">
  </pages>
</configuration>
Mahdi jokar
  • 1,227
  • 6
  • 29
  • 48
24

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.

function AlphanumericValidation(evt)
{
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
        ((evt.which) ? evt.which : 0));

    // User type Enter key
    if (charCode == 13)
    {
        // Do something, set controls focus or do anything
        return false;
    }

    // User can not type non alphanumeric characters
    if ( (charCode <  48)                     ||
         (charCode > 122)                     ||
         ((charCode > 57) && (charCode < 65)) ||
         ((charCode > 90) && (charCode < 97))
       )
    {
        // Show a message or do something
        return false;
    }
}

Then in code behind, on the PageLoad event, add the attribute to your control with the next code:

Me.TextBox1.Attributes.Add("OnKeyPress", "return AlphanumericValidation(event);")
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
  • 4
    This will still leave the app vulnerable from made-up POST requests. A regular user will have problems entering characters like , : or quotes, but a regular hacker will have no problems POSTing malformed data to the server. I'd vode this waaay down. – Radu094 Oct 26 '09 at 22:21
  • 14
    @Radu094: This solution allows you to keep ValidateRequest=true, which means hackers will still hit that wall. Vote UP, since this leaves you less vulnerable than turning ValidateRequest off. – jbehren Aug 17 '11 at 19:10
21

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.

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Example.aspx.vb" Inherits="Example.Example" **ValidateRequest="false"** %>

I don't know if there are any downsides, but for me this worked amazing.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Piercy
  • 749
  • 10
  • 31
20

Another solution is:

protected void Application_Start()
{
    ...
    RequestValidator.Current = new MyRequestValidator();
}

public class MyRequestValidator: RequestValidator
{
    protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
    {
        bool result = base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);

        if (!result)
        {
            // Write your validation here
            if (requestValidationSource == RequestValidationSource.Form ||
                requestValidationSource == RequestValidationSource.QueryString)

                return true; // Suppress error message
        }
        return result;
    }
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Sel
  • 1,774
  • 1
  • 19
  • 13
  • Nice! Wasn't aware of the ability to replace the Request Validator. Instead of just saying "ok" like you do I extended this idea to not validate fields that end in "_NoValidation" as their name. Code below. – Walden Leverich May 01 '14 at 20:01
  • Walden Leverich, to do this see [AllowHtml] attribure – Sel Jan 28 '15 at 09:10
  • Sel, yes in an MVC environment that would work. But in a webforms application I don't have a model to do that on. :-) – Walden Leverich Jan 29 '15 at 23:24
15

If you're using framework 4.0 then the entry in the web.config (<pages validateRequest="false" />)

<configuration>
    <system.web>
        <pages validateRequest="false" />
    </system.web>
</configuration>

If you're using framework 4.5 then the entry in the web.config (requestValidationMode="2.0")

<system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" requestValidationMode="2.0"/>
</system.web>

If you want for only single page then, In you aspx file you should put the first line as this :

<%@ Page EnableEventValidation="false" %>

if you already have something like <%@ Page so just add the rest => EnableEventValidation="false" %>

I recommend not to do it.

Durgesh Pandey
  • 1,936
  • 4
  • 25
  • 40
14

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

Display friendly message:

protected override void OnError(EventArgs e)
{
    base.OnError(e);
    var ex = Server.GetLastError().GetBaseException();
    if (ex is System.Web.HttpRequestValidationException)
    {
        Response.Clear();
        Response.Write("Invalid characters."); //  Response.Write(HttpUtility.HtmlEncode(ex.Message));
        Response.StatusCode = 200;
        Response.End();
    }
}
Jaider
  • 12,387
  • 5
  • 59
  • 77
14

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.

Disabling the protection on a per page level and then encoding each time is a better option.

Rather than using Server.HtmlEncode you should look at the newer, more complete Anti-XSS library from the Microsoft ACE team.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
blowdart
  • 52,422
  • 11
  • 102
  • 145
12

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():

<textarea id="userbox"  onchange="boo();"></textarea>

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:

<asp:HiddenField ID="hidHTML" runat="server" />
<textarea id="txtHTML"></textarea>
<asp:Button ID="btnMyPostbackButton" runat="server" Text="Post Form" />

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Jason Shuler
  • 369
  • 2
  • 6
  • This is a good solution. It's a proper manual way to control it yourself and not invalidate the entire website or page – Fandango68 Mar 18 '15 at 04:16
  • Make sure to use an HTML markup, not an ASP.Net control (ie no runat="server") for the textarea, then use the ASP.Net hidden control for the hidden. This is the best solution I've seen w/o compromising anything. Naturally, you want to parse your data for XSS, SQL Injection on the server side, but at least you can post HTML – MC9000 Jun 13 '15 at 07:50
  • `escape(...)` can take a long time. In my case, the markup was an entire (2MB) XML file. You might ask, "Why don't you just use ` – The Red Pea Sep 12 '16 at 18:18
12

Cause

ASP.NET by default validates all input controls for potentially unsafe contents that can lead to cross-site scripting (XSS) and SQL injections. Thus it disallows such content by throwing the above exception. By default it is recommended to allow this check to happen on each postback.

Solution

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 @Page directive to false.

<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest = "false" %>

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 <system.web> section

<pages validateRequest ="false" />

For .NET 4.0 or higher frameworks you will need to also add the following line in the <system.web> section to make the above work.

<httpRuntime requestValidationMode = "2.0" />

That’s it. I hope this helps you in getting rid of the above issue.

Reference by: ASP.Net Error: A potentially dangerous Request.Form value was detected from the client

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
vakeel
  • 272
  • 2
  • 7
10

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.

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

    protected override void Execute(RequestContext requestContext)
    {
        // Disable requestion validation (security) across the whole site
        ValidateRequest = false;
        base.Execute(requestContext);
    }

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
magritte
  • 6,801
  • 8
  • 52
  • 78
9

I was getting this error too.

In my case, a user entered an accented character á in a Role Name (regarding the ASP.NET membership provider).

I pass the role name to a method to grant Users to that role and the $.ajax post request was failing miserably...

I did this to solve the problem:

Instead of

data: { roleName: '@Model.RoleName', users: users }

Do this

data: { roleName: '@Html.Raw(@Model.RoleName)', users: users }

@Html.Raw did the trick.

I was getting the Role name as HTML value roleName="Cadastro b&#225;s". This value with HTML entity &#225; was being blocked by ASP.NET MVC. Now I get the roleName parameter value the way it should be: roleName="Cadastro Básico" and ASP.NET MVC engine won't block the request anymore.

Leniel Maccaferri
  • 94,281
  • 40
  • 348
  • 451
9

Disable the page validation if you really need the special characters like, >, , <, etc. Then ensure that when the user input is displayed, the data is HTML-encoded.

There is a security vulnerability with the page validation, so it can be bypassed. Also the page validation shouldn't be solely relied on.

See: http://web.archive.org/web/20080913071637/http://www.procheckup.com:80/PDFs/bypassing-dot-NET-ValidateRequest.pdf

Jack91255
  • 49
  • 4
woany
  • 1,199
  • 2
  • 10
  • 9
8

You could also use JavaScript's escape(string) function to replace the special characters. Then server side use Server.URLDecode(string) to switch it back.

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.

Trisped
  • 5,316
  • 2
  • 39
  • 50
7

I ended up using JavaScript before each postback to check for the characters you didn't want, such as:

<asp:Button runat="server" ID="saveButton" Text="Save" CssClass="saveButton" OnClientClick="return checkFields()" />

function checkFields() {
    var tbs = new Array();
    tbs = document.getElementsByTagName("input");
    var isValid = true;
    for (i=0; i<tbs.length; i++) {
        if (tbs(i).type == 'text') {
            if (tbs(i).value.indexOf('<') != -1 || tbs(i).value.indexOf('>') != -1) {
                alert('<> symbols not allowed.');
                isValid = false;
            }
        }
    }
    return isValid;
}

Granted my page is mostly data entry, and there are very few elements that do postbacks, but at least their data is retained.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Ryan
  • 71
  • 1
  • 1
  • There should be big brackets instead of small brackets. Like ` if (tbs[i].type == 'text') {` in place of ` if (tbs(i).type == 'text') {` – Shilpa Soni Sep 12 '14 at 05:18
6

You can use something like:

var nvc = Request.Unvalidated().Form;

Later, nvc["yourKey"] should work.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Ady Levy
  • 151
  • 2
  • 3
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.

maozx
  • 311
  • 4
  • 5
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.

Mike S.
  • 51
  • 1
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);
    }
}
Community
  • 1
  • 1
Walden Leverich
  • 4,190
  • 2
  • 19
  • 29
4

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

 public class AppModelBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            try
            {
                return base.CreateModel(controllerContext, bindingContext, modelType);
            }
            catch (HttpRequestValidationException e)
            {
                HandleHttpRequestValidationException(bindingContext, e);
                return null; // Encode here
            }
        }
        protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext,
            PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
        {
            try
            {
                return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
            }
            catch (HttpRequestValidationException e)
            {
                HandleHttpRequestValidationException(bindingContext, e);
                return null; // Encode here
            }
        }

        protected void HandleHttpRequestValidationException(ModelBindingContext bindingContext, HttpRequestValidationException ex)
        {
            var valueProviderCollection = bindingContext.ValueProvider as ValueProviderCollection;
            if (valueProviderCollection != null)
            {
                ValueProviderResult valueProviderResult = valueProviderCollection.GetValue(bindingContext.ModelName, skipValidation: true);
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
            }

            string errorMessage = string.Format(CultureInfo.CurrentCulture, "{0} contains invalid symbols: <, &",
                     bindingContext.ModelMetadata.DisplayName);

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorMessage);
        }
    }

In Application_Start:

ModelBinders.Binders.DefaultBinder = new AppModelBinder();

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.

Dangerous chars in URL may be handled this way:

private void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    HttpContext httpContext = HttpContext.Current;

    HttpException httpException = exception as HttpException;
    if (httpException != null)
    {
        RouteData routeData = new RouteData();
        routeData.Values.Add("controller", "Error");
        var httpCode = httpException.GetHttpCode();
        switch (httpCode)
        {
            case (int)HttpStatusCode.BadRequest /* 400 */:
                if (httpException.Message.Contains("Request.Path"))
                {
                    httpContext.Response.Clear();
                    RequestContext requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
                    requestContext.RouteData.Values["action"] ="InvalidUrl";
                    requestContext.RouteData.Values["controller"] ="Error";
                    IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
                    IController controller = factory.CreateController(requestContext, "Error");
                    controller.Execute(requestContext);
                    httpContext.Server.ClearError();
                    Response.StatusCode = (int)HttpStatusCode.BadRequest /* 400 */;
                }
                break;
        }
    }
}

ErrorController:

public class ErrorController : Controller
 {
   public ActionResult InvalidUrl()
   {
      return View();
   }
}   
Sel
  • 1,774
  • 1
  • 19
  • 13
  • Came here just to post this. Pity it's going to remain forever buried on the second page - this is, IMHO, the best solution. – PJ7 May 02 '18 at 13:03
4

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

Wahid Masud
  • 873
  • 9
  • 25
4

As long as these are only "<" and ">" (and not the double quote itself) characters and you're using them in context like <input value="this" />, you're safe (while for <textarea>this one</textarea> you would be vulnerable of course). That may simplify your situation, but for anything more use one of other posted solutions.

Paweł Hajdan
  • 16,853
  • 9
  • 45
  • 63
4

If you're just looking to tell your users that < 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?

Captain Toad
  • 329
  • 1
  • 10
3

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

More info here

bastos.sergio
  • 6,456
  • 4
  • 23
  • 33
2

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>
Magnus
  • 1,028
  • 11
  • 11
  • You should assume any code that runs on the client will be subverted. – user169771 Apr 05 '18 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 05 '18 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.

figolu
  • 938
  • 8
  • 5
1

Use the Server.HtmlEncode("yourtext");

RandomUs1r
  • 3,636
  • 1
  • 18
  • 38
Voigt
  • 59
  • 2
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!)

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Peter
  • 33,550
  • 33
  • 138
  • 185
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;

dpant
  • 1,375
  • 13
  • 27
1

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

<system.web>
     <httpRuntime requestValidationMode="2.0" />
c24w
  • 6,077
  • 6
  • 35
  • 46
Kiran Chaudhari
  • 459
  • 5
  • 4
1

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;
 }
Chris Catignani
  • 3,857
  • 6
  • 29
  • 40
  • 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. – Chris Catignani Jan 09 '19 at 13:53
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.

Sanjeev Singh
  • 3,690
  • 2
  • 29
  • 38
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="<>" />
syntap
  • 783
  • 5
  • 3
-1

Try with

Server.Encode

and

Server.HtmlDecode while sending and receiving.

Devendra Patel
  • 185
  • 1
  • 9
  • 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 '15 at 07:47