I'm trying to redirect to a custom page when there's an error. So I added to the Web.Config the following code
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Views/Error/Error500.cshtml"> <error statusCode="404" redirect="~/Views/Error/Error404"/> <error statusCode="500" redirect="~/Views/Error/Error500"/> </customErrors> </system.web> <system.webServer> <httpErrors errorMode="Custom" existingResponse="Replace"> <remove statusCode="404" subStatusCode="-1" /> <error statusCode="404" path="~/Views/Error/Error404" responseMode="ExecuteURL" /> <remove statusCode="500" subStatusCode="-1" /> <error statusCode="500" path="~/Views/Error/Error500" responseMode="ExecuteURL" /> </httpErrors> But when I try localhost:23920/aFakeURl it redirects me to a blank page and it doesn't reach my ErrorController.
If I try localhost:23920/Error/Error404 it goes in my controller
// GET: /Error/Error404 public ActionResult Error404() { Response.StatusCode = 404; return View(); } then it returns a statusCode 404 and IIS doesn't know what to do with it and it gives me a blank page. So I'm pretty sure the problem is the path in the Web.Config.
I tried
~/Views/Error/Error404"~/Views/Error/Error404.cshtml"/Views/Error/Error404"/Views/Error/Error404.cshtml"
It might be good to mention that when the path doesn't have a ~ it returns a runtime exception instead of a blank page.
So I have 2 questions.
- What's the proper way to write the
Web.Config? - Should I return the proper status code like this
Response.StatusCode = 404;in theErrorController?
Thank you
I don't know if it's good to mention but I use Elmah for error handling and logging. No idea if it has something to do with this problem but I read in their documentation that it should work with mode="On". Is there a better way to handle all this?
EDIT
Now I use this
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="/Error/Error500"> <error statusCode="404" redirect="/Error/Error404"/> <error statusCode="500" redirect="/Error/Error500"/> </customErrors> </system.web> <system.webServer> <httpErrors errorMode="Custom" existingResponse="Replace"> <remove statusCode="404" subStatusCode="-1" /> <error statusCode="404" path="/Error/Error404" responseMode="ExecuteURL" /> <remove statusCode="500" subStatusCode="-1" /> <error statusCode="500" path="/Error/Error500" responseMode="ExecuteURL" /> </httpErrors> but it always return an error 500 when I type a bad url.
The exception is System.Web.HttpException: The controller for path '/aBadUrllllll' was not found or does not implement IController.
How come this doesn't return a 404 error?
Do I have to change something in the Route.config?