ASP.NET MVC - MapRoute versus routes.Add (and 404s)

前端 未结 3 1371
悲哀的现实
悲哀的现实 2021-02-02 12:28

I\'m just getting started with ASP.NET MVC.

What is the difference between MapRoute and routes.Add ? Should I just be using MapRoute? Can I map multiple routes? Which \"

相关标签:
3条回答
  • 2021-02-02 12:45

    Use!

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            routes.MapRoute(
                "User",                                                     
                "User/{domain}/{username}",                           
                new { controller = "User", action = "Index", username= UrlParameter.Optional }      
            );
    
           }
    
        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
    
    0 讨论(0)
  • 2021-02-02 12:59

    Your User controller should have

    public class UserController : Controller {
        public ActionResult Index(string domain, string username) { return View(); }
    }
    

    The two variables on the Index method of the user controller get picked up from the route.

    0 讨论(0)
  • 2021-02-02 13:07

    MapRoute() is an extension method over Routes.Add(). Use MapRoute(), unless you need to do something more complex than it allows.

    Routes are evaluated in the order they are defined, so those you called first.

    0 讨论(0)
提交回复
热议问题