Search code examples
asp.netasp.net-mvcmvcroutehandler

.NET MVC URL Routing Help


I am trying to configure an ErrorController in my .NET MVC application, and I am unable to hit any actions on the controller currently, so I believe it may be because I need to register the URL route in the global.asax

The Error controller is the following:

public class ErrorController: Controller
{

    /*Default Redirect Error Page*/
    public ActionResult Index()
    {
        return View();
    }
    /*Generic Error Page*/
    public ActionResult Generic()
    {
        return View();
    }
    /*Status Code: 400*/
    public ActionResult NotFound()
    {
        return View();
    }
}

I would like to be able to call the actions above by the following URL's respectively.

~/Error/
~/Error/Generic
~/Error/NotFound

I would believe that in the Global.asax file I would need to register these routes using something like the following:

routes.Add(new Route("error/{action}", new MvcRouteHandler())){controller = "Error", action = "";

How would I add/specify the correct route handler for this?


Solution

  • I believe that the default url provided in global.asax would work for your url but if you want a specific url then go for:

    routes.MapRoute(
          "Error", // Route name
          "error/{action}", // URL without parameters
           new { controller = "Error", action = "Index" }, // Parameter defaults
    );
    

    and if you want parameters:

    routes.MapRoute(
          "Error", // Route name
          "error/{action}/{param}", // URL with parameters
           new { controller = "Error", action = "Index", param = UrlParameter.Optional }, // Parameter defaults
    );