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

a potentially dangerous request.form value was detected from the client mvc razor
a potentially dangerous request.form value was detected from the client javascript
a potentially dangerous request.form value was detected from the client ckeditor
a potentially dangerous request.form value was detected from the client bypass
a potentially dangerous request.form value was detected from the client &#
a potentially dangerous request.form value was detected from the client tinymce
a potentially dangerous request form value was detected from the client validaterequest not working
a potentially dangerous request.form value was detected from the client cshtml

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?

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

More info here

Avoiding the 'A potentially dangerous Request.Form value was , Avoiding the 'A potentially dangerous Request.Form value was detected'. January 28, 2013 By _tasos 3 The client side code. // The event to escape the data  This error can occur in any page, but mostly a client receives this error while entering a new or modified item / product in admin panel of any portal because in

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();
   }
}   

ASP.NET 4.0 potentially dangerous Request.Form value was detected, "A potentially dangerous Request.Form value was detected from the client". This was because .NET detected something in the entered text which looked like an  Avoiding the ‘A potentially dangerous Request.Form value was detected’ is to encode the HTML in the client side and then decode it in the server side

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);
    }
}

[Solved] A potentially dangerous Request.Form value was detected , Form value was detected from the client (txtAnsDesc="<br>"). Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. Possible duplicate of A potentially dangerous Request.Form value was detected from the client, doesn't matter if it's Webforms or MVC. – Erik Philips Jun 22 '13 at 20:05. Thanks, but you havent looked at my issue as its different – D-W Jun 23 '13 at 17:04.

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.

A Potentially Dangerous Request.form Value Was Detected From , How to prevent the Exception "A potentially dangerous Request.Form -​dangerous-request-form-value-was-detected-from-the-client?rq=1. 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.

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.

ASP.Net Error: A potentially dangerous Request.Form value was , The error exception A potentially dangerous Request.Form value was detected from the client occurs when ValidateRequest is set true and  Web API: A potentially dangerous Request.Path value was detected from the client 1 Is there a configuration on IIS to avoid showing “A potentially dangerous Request.Path value was detected from the client (:).”

A potentially dangerous Request.Form value was detected, Form value was detected from the client (ctl00$MainContent$TextBox1="<a"). Description: ASP.NET has detected data in the request that  Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack.

System.Web.HttpRequestValidationException: A potentially , A potentially dangerous Request.Form value was detected from the client. Frankly speaking, blocking potentially dangerous charaters isn't a  A potentially dangerous Request.Form value was detected from the client. The error exception A potentially dangerous Request.Form value was detected from the client occurs someone tries to submit HTML or JavaScript code to server. Such exception comes since ASP.Net MVC has inbuilt mechanism to prevent XSS (Cross Site Scripting) attacks.

so then it caused the form to crash. “System.Web.​HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client”

Comments
  • Note that you can get this error if you have HTML entity names (&amp;) or entity numbers (&#39;) in your input too.
  • 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
  • @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 &#)
  • 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[!").
  • TL;DR put <httpRuntime requestValidationMode="2.0" /> in web.config
  • Use the Anti-XSS Library to prevent this error... this is incomplete.
  • Giving a little more explanation on how to do this might be helpfull.
  • Came here just to post this. Pity it's going to remain forever buried on the second page - this is, IMHO, the best solution.
  • You should assume any code that runs on the client will be subverted.
  • @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..."
  • @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.
  • 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.