RouteAttribute broke my Default route

2019-09-21 11:22发布

问题:

If I apply [Route(Name = "WhatEver")] to action, which I use as Default site route, I get HTTP 404 when accesing site root.

For example:

  • Create new sample MVC project.
  • Add attributes routing:

    // file: App_Start/RouteConfig.cs
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes(); // Add this line
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
    
  • Add routing attributes

    [RoutePrefix("Zome")]
    public class HomeController : Controller
    {
        [Route(Name = "Zndex")]
        public ActionResult Index()
        {
            return View();
        }
        ...
    }
    

And now, when you start your project for debuging, you will have HTTP Error 404. How should I use attribute routing with default route mapping?

回答1:

For default route using attribute routing with route prefix you need to set the route template as an empty string. You can also override the site root using ~/ if the controller already has a route prefix.

[RoutePrefix("Zome")]
public class HomeController : Controller {
    [HttpGet]
    [Route("", Name = "Zndex")]      //Matches GET /Zome
    [Route("Zndex")]                 //Matches GET /Zome/Zndex
    [Route("~/", Name = "default")]  //Matches GET /  <-- site root
    public ActionResult Index() {
        return View();
    }
    //...
}

That said, when using attribute routing on a controller it no longer matches convention-based routes. The controller is either all attribute-based or all convention-based that do not mix.

Reference Attribute Routing in ASP.NET MVC 5



回答2:

When you start your site there is a default route set in the route.config file in the App_Start folder. It looks something like this:

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

If you no longer have an "index" action in your home controller the site tries in vain to fin that as the home page and will return a 404. You can update your route.config file to reference the new home page.