I am trying to figure out how to handle errors correctly in ASP.NET MVC4. As an example, I created a new MVC4 project using the "Internet Application" template and updated my home controller to check for some errors:
public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Hello"; return View(); } public ActionResult About() { throw new HttpException(401, "Not Authorized"); } public ActionResult Contact() { throw new Exception("Oh no, some error occurred..."); } }
I included customErrors in my web.config file:
<customErrors mode="On"></customErrors>
When I launch the application and click on "Contact", I see the view ~ / Views / Shared / Error.cshtml, as expected, since I have a HandleErrorAttribute registered as a global filter.
However, when I click βOβ, I get a standard ASP.NET error page that says βRuntime Errorβ. Why are these two exceptions handled differently and how can I get HttpException instances to be caught using the HandleError attribute?
CustomErrors Configuration
Ideally, I would like custom error pages to display as follows:
- User page 404 (not found), which is convenient and user friendly.
- User 401 (unauthorized) page informing the user that they do not have access (for example, after checking permissions for a specific element in the model)
- A common error page that is used in all other cases (instead of the standard yellow ASP.NET page).
I created a new Error controller with views for each of the scenarios described above. Then I updated customErrors in web.config as follows:
<customErrors mode="On" defaultRedirect="~/Error/Trouble"> <error statusCode="404" redirect="~/Error/NotFound"></error> <error statusCode="401" redirect="~/Error/NotAuthorized"></error> </customErrors>
Page 404 works fine, but I don't get page 401 at all . Instead, I get the view ~ / Error / Trouble (the one that is specified as defaultRedirect ) when I try to access the About action on the Home controller.
Why is my custom 401 redirect page not working?