Handle validation failures myself in ASP.NET MVC

后端 未结 2 1980
心在旅途
心在旅途 2021-01-21 03:23

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 hand

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-21 03:37

    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
    

提交回复
热议问题