Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
362 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...