Search code examples
c#asp.net-mvcasp.net-mvc-routing

Returning a 404 when the URL does not contain Index


I am having trouble with routing in MVC. I have created a controller for my contact page, but unless I specify the route as /contact/index it will return a 404. I cannot see why it can't find the View with just /contact in the URL. My RouteConfig looks fine to me.

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "T",
                url: "T/{action}",
                defaults: new { controller = "Home", action = "Index" }
            );

            routes.MapRoute(
                name: "Holding",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Holding", id = UrlParameter.Optional }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

The only reason I can see it not finding its View is because of the new Route I have configured to display a site holding page. Interestingly /t does display the 'demo' homepage, so I can't see why it doesn't like just /contact.

This S.O article told me that I could fix the problem by giving it its own MapRoute but I shouldn't have to do all that?

public class HomeController : Controller
{
     public ActionResult Index()
     {
        return View();
     }

     public ActionResult Holding()
     {
         return View();
     }
}

public class ContactController : Controller
{
    // GET: Contact
    public ActionResult Index()
    {
        return View();
    }
}

It must be something silly, but I can't work it out.


Solution

  • You have route conflicts

    /contact would match

    routes.MapRoute(
        name: "Holding",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Holding", id = UrlParameter.Optional }
    );
    

    But since contact controller has no Holding action you will get a 404 Not Found

    And since it matched the Holding route it wont go on to the next Default route as first match wins.

    The added route is too general so it will get a lot of false matches.

    Based on the controllers shown, the added route is not needed. the holding path would still match the default route template. So it can actually be removed altogether.