Paul
Paul

Reputation: 23

How do I handle a HttpRequestValidationException and return a meaningful error using AddModelError?

I would like to handle HttpRequestValidationExceptions (e.g. when html is inserted into form fields) and return the user back to the page after submission with a meaningful error to highlight the problem.

For example, on a login page, if the user types some invalid characters into the username field, then I would like to catch the HttpRequestValidationException and return the user to the login page with the username field highlighted.

I can catch the error in a class inheriting from HandleErrorAttribute using the OnException method.

Is there a way from here (or any other way) that I can get the Controller *ModelState* to add the error?

Note: I do not want to turn validation off or redirect to an error page.

e.g.:

public override void OnException(ExceptionContext filterContext)
{
    if (filterContext.Exception is HttpRequestValidationException)
        {
            ModelStateDictionary ModelState = <...>
            ModelState.AddModelError("Error", "Invalid chars");
            filterContext.HttpContext.Response
            filterContext.ExceptionHandled = true;
            HttpContextBase HttpContext = filterContext.HttpContext;
            HttpContext.Response.Redirect(HttpContext.Request.Path);

            return;
        }
}

Thanks in advance for any help you can give me!

Upvotes: 2

Views: 965

Answers (1)

Prutswonder
Prutswonder

Reputation: 10064

Instead of capturing and handling the HttpRequestValidationException, you could decorate your model's properties with the [AllowHtml] data annotation and your own custom data annotation, which contains the validation rules you require. See this answer for a good example.

Your model's properties may look like this:

[AllowHtml]
[DisallowHtml]
public string SomeProperty{ get; set; }

Which looks a bit silly, but so far it's the cleanest solution I've encountered.

Upvotes: 1

Related Questions