Handle validation errors yourself in ASP.NET MVC

We all know that the familiar ASP.NET error page that we see many times during development. In order to constantly monitor my site, I would prefer that the user not see these errors and deal with them himself. For most of everything, I can catch the exception and return my own error page, and we're all happy.

Except for one scope of the request validation. This annoys me because the exception is thrown before the request ever reaches the controller, so I can catch and handle it myself.

I can add "[ValidateInput (false)]" to my method to force invalid requests, but obviously this disables the required validation check. I was advised to use "ModelState.IsValid" in conjunction with a manual call to validate the input, but IsValid just seems to just always return "false" which doesn't help.

How can I get the standard input validation to pass in my controller action and not before?

+3


source to share


2 answers


Request validation is not the same as model validation. Request validation (which you can disable with [ValidateInput(false)]

) tries to protect potentially unsafe user input from reaching your controller / action method. This is why an exception is thrown from the request pipeline before the input ever reaches your controller.

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



However, you can probably handle the error and redirect to the custom error page 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

      

+3


source


Create one basic controller. Add [ValidateInput (false)] to your controller class:

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

 }

      

And then update each controller to inherit it:



 public class HomeController : BaseController
 {

 }

      

I am not suggesting that you turn off request validation yourself, but if you need to, you can.

0


source







All Articles