9

I'm trying to have 2 custom error pages in a stock sample ASP.NET MVC3 website.

Darin Dimitrov has a good SO answer here but it's not working for all my test conditions.

Then there is the widely popular How can I properly handle 404s in ASP.NET MVC? post .. but this just touches on a 404 error.

Can someone please explain what

  • Routes
  • web.config settings
  • controllers / action methods

are required to do this very simple thing :(

Scenarios to accept this answer:

  • VS2010 -> File -> New -> ASP.NET MVC3 project / Internet Application
  • (Right Click on the solution).. -> Use IIS Express
  • Error pages cannot be a static html page. They must be a page which I can pass info to, like any other view, etc. (eg. an ErrorController)...

and for the test routes...

  • /Home/Index -> shows index page
  • /Home -> shows index page
  • / -> shows index page
  • /Home/About -> shows about page
  • /asdasd/asdsad/asdas/asddasd/adsad -> 404
  • /adsa/asda/asd/asd/asd/asd -> 404
  • /asdsadasda -> 404

then add this to the HomeController.cs class..

public ActionResult ThrowException()
{
    throw new NotImplementedException();
}

and now ..

  • /home/throwexception -> 500 error

Cheers :)

BTW, some of those realy long routes (above) give really weird error pages right now, when using the stock standard new ASP.NET MVC3 template

Community
  • 1
  • 1
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
  • Pure.Krome, are you basically concerned with the 500 error? In your second link, the post by Cottsak handles all of the above 404 scenarios as hoped. – Khepri May 30 '11 at 08:19
  • It's a pretty good solution .. but as I asked - what about 404 and 500? This stuff should be backed into the framework AND be one of the first tutorials, I would have thought. A static page, IMO, is not good enough :( Sure it might have a pretty fail wail, but sometimes we need a wee bit more logic. – Pure.Krome May 30 '11 at 09:03
  • have you looked at my answer Pure.Krome? it allows you to redirect a specific error code to any route. You can even set the status code in the action if you want to be "correct" – The_Butcher May 30 '11 at 09:13
  • Pure.Krome, I've been thinking about this more and would a custom attribute that inherits from HandleErrorAttribute work for your requirements? See http://stackoverflow.com/questions/5742141/system-web-mvc-handleerrorinfo-wrong-model-type. The gist of it is you implement your own version of HandleError that allows you to implement your own model instead of the base System.Web.Mvc.HandleErrorInfo model. You could set whatever data you wanted allowing you to pass information to the 500 view. – Khepri May 30 '11 at 17:15
  • @Khepri - that would work great if u want to use the built in stuff for HandleError (ie. extending the model). That's a great problem to have ... I'm still stuck with getting some basic 404 AND 500 error handling for all those scenario's .. let alone customizing the view. – Pure.Krome May 31 '11 at 06:50
  • Ok, well let's back up. For the 404 functionality, which model have you implemented? Did you go the Cottsak route from your original post or the Darin Dimitrov option? I've implemented the Cottsak route. What particularly are you banging your head against? – Khepri May 31 '11 at 20:18
  • @Khepri - i've given Cottsak's suggestion a go .. taking it one step further with a NuGet package called NotFound MVC (http://nuget.org/List/Packages/NotFoundMvc/0.1.0). Which is great and works well .. for most of the time. My simple API website -> fine. My more complex main website with areas and around 23 routes .. nope. Simple (404) routes fail (shows the ASP.NET 404 error page). crazy long 404 routes, works fine. My point -> this shit is waaaaaaay too hard when it -should not be- :( And it's foundation framwork stuff, also! :~~~( – Pure.Krome Jun 01 '11 at 04:31

3 Answers3

6

I specify customErrors in my web.config file as below;

    <customErrors defaultRedirect="/Error/GeneralError" mode="On">
      <error statusCode="403" redirect="/Error/403" />
      <error statusCode="404" redirect="/Error/404" />
      <error statusCode="500" redirect="/Error/500" />
    </customErrors

I have a route in the Global.asax as below;

            /// Error Pages
            /// 
            routes.MapRoute(
                "Error", // Route name
                "Error/{errorCode}", // URL with parameters
                new { controller = "Page", action = "Error", errorCode= UrlParameter.Optional }
            );

The corresponding ActionResult does the following, which returns the relevant custom error page.

//
        public ActionResult Error(string errorCode)
        {
            var viewModel = new PageViewModel();

            int code = 0;
            int.TryParse(errorCode, out code);

            switch (code)
            {
                case 403:
                    viewModel.HtmlTitleTag = GlobalFunctions.FormatTitleTag("403 Forbidden");
                    return View("403", viewModel);
                case 404:
                    viewModel.HtmlTitleTag = GlobalFunctions.FormatTitleTag("404 Page Not Found");
                    return View("404", viewModel);
                case 500:
                     viewModel.HtmlTitleTag = GlobalFunctions.FormatTitleTag("500 Internal Server Error");
                    return View("500", viewModel);
                default:
                    viewModel.HtmlTitleTag = GlobalFunctions.FormatTitleTag("Embarrassing Error");
                    return View("GeneralError", viewModel);
            }
        }

This allows me to have many different custom error pages. It's maybe not the best or most elegant solution, but it certainly works for me.

macou
  • 777
  • 8
  • 21
  • 1
    There is a problem - you replace the initial query with your 404page's url, which is certainly bad for user. – Alleo Sep 11 '11 at 07:27
  • I tried to implement this, but it fails for error 400, any ideas? I simply get the standard error page instead of the one I specify in ``. – Joel Peltonen Aug 13 '12 at 11:40
  • 1
    I may be wrong and someone please correct me if I am, but I didn't think 400 errors were customisable? – macou Aug 14 '12 at 00:16
  • Quick question, why wouldn't you put that Route in the App_Start > RouteConfig.cs file? – Termato Aug 27 '14 at 19:48
  • 1
    @Termato, you would now in 2014, but back then the routes were in the global.asax file. – macou Aug 29 '14 at 03:06
0

You can set your error page information in the web.config. This page talks about doing this and using the HandleErrorAttribute set on your controllers so they use this configuration.

http://deanhume.com/Home/BlogPost/custom-error-pages-in-mvc/4

Chris Woolum
  • 2,854
  • 20
  • 20
0

This seems to be a big question here.

See my answer is this post:

Once and for all what is the best routing approach to handle errors, exceptions and 404's in MVC

But i would add these routes to your test cases:

http://www.website.com/yourcontroller/youraction:32

and

http://www.website.com/yourcontroller/youraction/http:/www.website.com/yourcontroller/youraction?par=123

Community
  • 1
  • 1
Softlion
  • 12,281
  • 11
  • 58
  • 88