MVC3 Routing Basics

会有一股神秘感。 提交于 2019-12-03 09:04:12

First, we need some definitions here.

Let's break down the default route.

routes.MapRoute( 
    "Default", // Route name 
    "{controller}/{action}/{id}", // URL with parameters 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
); 

In this case, Default, on line 2, is merely a text name used to identify the route.

On line 3 is the url pattern. This defines how the route is matched. the things in braces are placeholders. They map to parameter names. so {controller} maps to the controller name. {action} maps to action name, and {id} maps to parameter called id.

On line 4 is the defaults object. This object supplies default values when they cannot be inferred from the url.

So, if we take all that together, here are some conclusions we can draw:

the default objects only supply values when they cannot be inferred from the url string. Thus, when the incoming request is just /, the dfault values from line 4 are used for controller and action. If the incoming request is /Blah, then the default controller supplied on line 4 is ignored, and instead MVC looks for BlahController. However, since no action was specified, the default action from line 4 is used Index.

The key thing to remember here is that the values on line 4 are only used if nothing matches the url in line 3.

So, when you changed everything, you threw everything for a loop. It's a meaningless route, because nothing defines which controller or action to use, and those two values are required in order to complete the route. As such, MVC can't figure out what controller you want. Or action method for that matter.

Another example:

routes.MapRoute(
    "Example",
    "Home/{action}/{myid}",
    new { controller = "NotHome", action = "Index", myid = UrlParameter.Optional }
);

Because there is no {controller} placeholder in the url, then the default of "NotHome" is used, which makes MVC look for NotHomeController. So a url of /Home/About/3 would mean that controller = "NotHome", action = "About", and myid = 3.

All in all, in an incoming route, something must fill in the value for controller and action at a minimum. id is optional, and can be renamed to whatever you like. But, something must set controller and action parameters or MVC doesn't know how to route things.

Also, remember, the default route (or an effective default route) must come last in the list, otherwise no other routes will be matched.

The {*pathInfo} bit is called a slug. it's basically a wildcard saying "everything after this point is stuffed into a parameter called pathInfo". Thus if you have "{resource}.axd/{*pathInfo}" and a url like this: http://blah/foo.axd/foo/bar/baz/bing then two parameters get created, one called resource, which would contain foo and one called pathInfo which contains foo/bar/baz/bing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!