3

We all know that familiar ASP.NET error page that we see many times during development. To keep a consistent feel to my site, I'd rather the user not see those errors, and handle them myself. For most everything, I can catch the exception and return my own error page, and we're all happy.

Except for one area, request validation. This is an annoying point for me, because the exception is thrown before the request ever reaches the controller, so I'm able to catch and handle it it myself.

I can add "[ValidateInput(false)]" to my method to force invalid requests through, but obviously this is disabling necessary validation checking. It was recommend to me that I use "ModelState.IsValid" in conjunction to manually invoke the input validation, but IsValid seems to be simply always returning 'false' which is no help.

How can I force the standard input validation to take place IN my controller action, and not before?

2 Answers 2

3

Request validation is not the same as model validation. Request validation (which you can disable using [ValidateInput(false)]) tries to protect potentially dangerous user input from ever reaching your controller / action method. This is why the exception is thrown from the request pipeline before the input ever reaches your controller.

I don't think you can change this pipeline behavior without forking the MVC WebRuntime source code and using your own personal branch of the MVC library. You shouldn't do that.

However, you can probably handle the error and redirect to a custom error page by using Application_Error in your global.asax.

var ex = Server.GetLastError();
if (ex == null) return;
if (ex.GetType() == typeof(HttpException) && ex.Message.StartsWith(
    "A potentially dangerous Request.Path value was detected from the client"))
    // redirect to your custom error page here
Sign up to request clarification or add additional context in comments.

Comments

0

Create a single base controller. Add [ValidateInput(false)] to the controller class:

 [ValidateInput(false)]
 public class BaseController : Controller
 {

 }

And then update every controller to inherit from it:

 public class HomeController : BaseController
 {

 }

I don't suggest turning off Request Validation myself but if you must, you can.

2 Comments

If you were going to turn it off for all controllers and all action methods, why not just add it as a global filter during Application_Start? public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new ValidateInputAttribute(false)); }
You may not want it for every single controller. You can also turn off request validation in the web.config. asp.net/whitepapers/request-validation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.