MVC中的Routing

Routing

ASP.NET Routing模块的责任是将传入的浏览器请求映射为特有的MVC controller actions。

public static void RegisterRoutes(RouteCollection routes)
{
    //忽略对.axd文件的Route,也就是和WebForm一样直接去访问.axd文件
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
    routes.MapRoute(
    "Category", // Route 的名称
    "Category/{action}/{categoryName}",// 带有参数的URL
    new { controller = "Category", action = "Index", categoryName = "4mvc" }// 设置默认的参数
    ); 
} 
protected void Application_Start()
{
    //在程序启动的时候注册我们前面定义的Route规则
    RegisterRoutes(RouteTable.Routes);
}

添加一个包含两个URL参数actioncategoryName的Route对象 

通常,我们在Global.asax文件中的Application_Start事件中添加routes,这确保routes在程序启动的时候就可用,而且也允许在你进行单元测试的时候直接调用该方法。如果你想在单元测试的时候直接调用它,注册该routes的方法必需是静态的同时有一个RouteCollection参数。

//忽略对.axd文件的Route,也就是和WebForm一样直接去访问.axd文件
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

添加约束条件,支持正则表达式。例如我们需要对id参数添加一个必须为数字的条件:

routes.MapRoute(
     "Default",                                              
     "{controller}/{action}/{id}",                           
     new { controller = "Home", action = "Index", id = "" },  
     new { id = @"[d]*" } //id必须为数字,使用星号(*)匹配不确定个数的参数,这会匹配URL后面所有的剩余的参数 ); 

Controller中的Action方法中有个return View()的方法。默认情况下它会返回与Action同名的view.在ASP.NET MVC默认的视图引擎(WebFormViewEngine)下,view是按如下路径访问的:

/Views/{Controller}/{Action}.aspx

也就是说对于http://localhost:2176/Home/Index这个路径,在默认情况下,在Index这个Action中用return View()来返回view的时候,会去寻找/Views/Home/Index.aspx文件,如果找不到这个文件,就会去Share目录中寻找:/Views/Share/Index.aspx,如果都找不到,就会抛出找不到View的异常。return View("Default.aspx")来指定要返回哪一个view:/Views/Home/Default.aspx。

如果url为query/{queryname}/{*queryvalues}

对于url:query/aspnetmvc/preview5/routing ,则queryvalues参数匹配的参数为 preview5/routing

下面是一些示例URL

Valid route definitions

Examples of matching URL

{controller}/{action}/{id}

/Products/show/beverages

{table}/Details.aspx

/Products/Details.aspx

blog/{action}/{entry}

/blog/show/123

{reporttype}/{year}/{month}/{day}

/sales/2008/1/5

url匹配Route是根据Route的定义顺序来自上而下匹配的,所以URL永远都匹配不了第二个Route。所以,在定义Route的时候,要将一些特别的Route放到前面

 最后感谢原文作者:QLeelulu的文章http://QLeelulu.cnblogs.com/

原文地址:https://www.cnblogs.com/loveAnimal/p/3333092.html