user2217261
user2217261

Reputation: 455

How to correctly handle System.Web.HttpRequestValidationException

System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client

When rising exception above usually suggest disable validation request with the attribute below

    [ValidateInput(false)]
    public ActionResult Save(string content)
    {
        System.IO.File.WriteAllText(fileName, content);
        return View();
    }

Then why even come up with this verification? How to correctly handle this exception?

Upvotes: 0

Views: 2933

Answers (1)

Hau Le
Hau Le

Reputation: 677

When the URL request (Your example: string content) contains the dangerous keywords :" >, ?, <, etc... ". If you want handle this exception (Example: allow these), you can follow sample code:

using System;
using System.Web.Mvc;

namespace Custom {
    public class CustomValidateInput : FilterAttribute, IAuthorizationFilter {
        /// <summary>
        /// Called when authorization is required.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        /// <exception cref="System.ArgumentNullException">filterContext</exception>
        public void OnAuthorization(AuthorizationContext filterContext) {
            if (filterContext == null) {
                throw new ArgumentNullException("filterContext");
            }

            //Set disable validation request
            filterContext.Controller.ValidateRequest = false;

            //----------Your code handle here------------//

        }
    }
}

and

[CustomValidateInput]
public ActionResult Save(string content)
{
    System.IO.File.WriteAllText(fileName, content);
    return View();
}

Upvotes: 1

Related Questions