ASP.NET MVC关键的一步就是路由配置了。
甚至有些时候路由决定了程序的难易程度。
这节,我们讲解一下一些在项目中用到的常用路由配置。
比如单页路由配置。比如我们希望我们的页面是http://www.xxxx.com/page/xxxx
这个xxx可以让我们任意配置
defaults: new { controller = “Home”,action=”Index”,page=”abc”, id = UrlParameter.Optional }
也就是在Application_Start里面我们是先注册区域路由Area
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
RouteData 必须包含名为“action”且值为非空字符串的项
当有两个同名的controller的时候 需要制定namespace
路由的先后顺序关系,特殊的路由要放上面。
路由器中的命名空间使用,比如有些controller是放在其他的dll中的
区域路由要放在上面。
理解路由配置的五个参数 name url defaults constraints
找到多个与名为“Page”的控制器匹配的类型。如果为此请求(“{page}”)提供服务的路由没有指定命名空间以搜索与此请求相匹配的控制器,则会发生这种情况。如果是这样,请通过调用带有 ‘namespaces’ 参数的 “MapRoute” 方法的重载来注册此路由。
“Page”请求找到下列匹配的控制器:
ClassLibrary1.PageController
WebApplication1.Controllers.PageController
路由配置代码示例
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//http://xxx.com/
routes.MapRoute(
name: "Home",
url: "",
defaults: new { controller = "Home", action = "Index"}
);
//http://xxx.com/abc
//http://xxx.com/ed
//http://xxx.com/oka
routes.MapRoute(
name: "Page",
url: "{page}",
defaults: new { controller = "Page", action = "Index", page = "abc" },
constraints:new {page="[a-z]+" },
namespaces:new string[]{ "ClassLibrary1"}
);
//http://xxx.com/abc/sadf
//http://xxx.com/abc/sadf/1
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}Code language: JavaScript (javascript)