ASP.NET MVC 4 Routes not working

HaBo picture HaBo · Mar 7, 2013 · Viewed 7.8k times · Source

Route

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

my controller

 public class HomeController : BaseController
    {
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }

My Global.asax

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }

Finally my request url

http://localhost:1234/Contact/

Error on browser

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Contact/

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18033

What am I doing wrong?

Solution:

Custom route should take the precedence

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

Answer

ssilas777 picture ssilas777 · Mar 7, 2013

The Framework always tries to match the URL of the request to a route in the order of the Routes added to the RouteCollection

So you should put the custom routes before the default route,

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