Home RouteAttribute broke my Default route
Reply: 2

RouteAttribute broke my Default route

vasily.sib
1#
vasily.sib Published in 2017-09-14 04:43:34Z

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?

Nkosi
2#
Nkosi Reply to 2017-09-14 18:12:51Z

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

Locke125
3#
Locke125 Reply to 2017-09-14 17:38:59Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.476042 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO