-->

ASP.NET MVC: How to handle 400 bad request error w

2019-02-24 03:25发布

问题:

I am trying to handle all HTTP errors to my custom error pages, but I find that when there is a % at the end of url, i cannot use config setting or code to handle it, for example: http://localhost/abc% the response is: Bad Request - Invalid URL HTTP Error 400. The request URL is invalid.

So, can we use config setting or c# code to handle this error request?

回答1:

See this 4 part series for configuring custom error pages within IIS: http://www.dotnetscraps.com/dotnetscraps/post/Did-you-know-Enable-Custom-Error-in-IIS-7-75.aspx.

I personally prefer to use Application_Error event to log the errors and redirect user to custom error pages. Note that you need to use integrated pipe-line in IIS to catch all errors otherwise IIS will show its own error page for resources that are not served by ASP.NET.

EDIT: Sorry for the wrong answer. I have XP machine currently that shows 404 for % sign so couldn't verify above. Searching over internet, I found that it's simply not possible to display custom error page for 400 status code. See this question from server fault for more information.



回答2:

Who said not possible?

Response.TrySkipIisCustomErrors = true;

OR

<configuration>
  <system.webServer>
    <httpErrors existingResponse="PassThrough" />
  </system.webServer>
</configuration>

original post