I like ASP.NET MVC 5's request validation feature. I want to keep it around. However it always causes Internal Error (500) responses to be returned to the client. That's not quite right; the real problem is that it's a bad request! I want to return a Bad Request (400) status code, and potentially a nicer-looking error page.
While I've found plenty of useful information on disabling request validation, or implementing your own custom validation logic, in all my searching I have yet to find a way to customize the response after a failed validation.
How do I do that? Is it possible?
EDIT: I'm not talking about model validation, I'm talking about request validation.
It looks to me like ASP.NET does return a Bad Request (400) error code if it internally encounters any suspicious characters in the request. For example, when ASP.NET tries to select a controller / action based on the request path, it will return a 400 error code if the path contains suspicious characters.
So when none of my code has even executed yet, ASP.NET handles it properly.
The Internal Server (500) error code only happens when my code encounters suspicious characters. For example, when I write...
var queryStringKeys = Request.QueryString.AllKeys.ToArray();
...the QueryString
property there throws an HttpRequestValidationException
if the query string contains suspicious characters. Leaving that exception unhandled makes ASP.NET return a 500 error (just like any other unhandled exception).
So the correct way to handle this is to use a try / catch statement, and in the catch block, return a Bad Request response yourself. I suppose you could also set up a filter of some sort that also handles the HttpRequestValidationException
for you globally.