一、介绍
Routing的作用:它首先是获取到View传过来的请求,并解析Url请求中Controller和Action以及数据,其次他将识别出来的数据传递
给Controller的Action(Controller的方法)。
Global.asax 路由配置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MyPeb.Mvc
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
//忽略对.axd文件的Route,也就是和WebForm一样直接去访问.axd文件
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//强字符串匹配 http://localhost/Category/Detail/Name
//注意:我们新的路由规则一定要放在前面,因为ASP.NET MVC会自上向下匹配第一条找到的可匹配路由规则。
routes.MapRoute(
"Category",
"Category/Detail/{name}",
new { controller = "Category", action = "Detail", name = "" }
);
//默认路由器
routes.MapRoute(//向系统增加一条路由规则
"Default", // 规则名
"{controller}/{action}/{id}", // 描述了如何解析url。可以这样理解,它描述了url串HostName后面部分如何匹配,其中带{}的表示参数匹配,如果不带{}则表示字符串匹配。
new { controller = "Home", action = "ExamPlan", id = UrlParameter.Optional } // 默认参数(首页)
);
//重要结论:在默认值被设置的情况下,映射规则“配少不配多”,少的部分由默认值代替。
}
protected void Application_Start()
{
ModelBinders.Binders.DefaultBinder = new MyPeb.Bll.Core.MyExamModelBinder();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);//将全局过滤器进行注册
RegisterRoutes(RouteTable.Routes);//在程序启动的时候,注册我们前面定义的Route规则
}
}
}
ModelBinders.Binders.DefaultBinder 获取或设置默认的模型联编程序(表明现在的默认模型绑定器用的是我们自己定义的)
实例1:带名称空间,带约束,带默认值的路由规则
函数头:MapRoute( string name, string url, object defaults, object constraints, string[] namespaces);
routes.MapRoute(
"Rule1",
"Admin/{controller}/{action}-{Year}-{Month}-{Day}",
new { controller = "Home", action = "Index", Year = "2010", Month = "04", Day = "21" },
new { Year = @"^\d{4}", Month = @"\d{2}" },//带约束
new string[] { "MvcDemo.Controllers" }//名称空间
);
Url:http://localhost:14039/Admin/home/index-2010-01-21
实例2:
routes.MapRoute(
"Default1", // Route name
"{controller}/{action}/{time}/{id}.html", // URL with parameters
new { controller = "Home", action = "Index" }, // Parameter defaults
new { id = "^[\\d]+$" }
);
Url:http://localhost:4700/Home/NewsDetail/2012-09-03/61.html
routes.MapRoute(
"Default2", // Route name
"{controller}/{action}.html", // URL with parameters
new { controller = "Home", action = "Index"} // Parameter defaults
);
Url:http://localhost:4700/Home/NewsList.html