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

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

c# - RouteAttribute broke my Default route

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...