Search code examples
asp.net-mvcasp.net-mvc-5.2

Why does web root give a 404 in ASP.Net MVC 5


I have an ASP.Net MVC 5 site where I changed the routes in the Home controller to remove the Home portion.

My Home Controller looks like

    [Route("Index")]
    public ActionResult Index()
    {
        ViewBag.Title = "Home";
        ViewBag.Current = "Home";

        return View();
    }

This works great when I go to http://localhost:29033/Index but when I go to http://localhost:29033 I get the following error:

A public action method 'Index' was not found on controller 'MyProject.Controllers.HomeController'.

My RegisterRoutes looks like:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.LowercaseUrls = true;

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("elmah.axd");

        routes.MapMvcAttributeRoutes();

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

Any help would be appreciated.


Solution

  • Given that it appears that attribute routing is being employed here I believe you need to update your routes to get the desired behavior

    [RoutePrefix("home")]
    public class HomeController : Controller {
    
        [Route("Index")] // Matches GET home/index
        [Route("~/", Name = "root")] //Matches GET /
        public ActionResult Index() {
            //...code removed for brevity
        }    
    
    }
    

    Reference Attribute Routing in ASP.NET MVC 5