MVC5.0-路由

  • Asp.net MVC 利用RouteTable.Routes静态对象将所有的路由规则保存下来,当浏览器传过来http请求时,就会比对RouteTable.Table来决定使用MvcHander来处理还是使用其他的HttpHander来处理。
  • 在Asp.netMVC4以前的版本中URL Routing是注册在Global.asax中的。 -定义路由时可以使用Namespaces命名空间,可以让网址路由在对比时指定命名空间进行对比:
route.MapRoute(
name:"About",//名称必须唯一
url:"{action}/{id}",
default:new
{
  controller="Home",
  action="Index",
  id=UrlParameter.Optional
  
}),
constraints:new {action="(About|contact)"},
//利用regex语法同时允许About和contact
namespaces:new[]{"WebApplication1.Controllers"}
//限制只有命名空间相同的才会比对成功
  • 可以使用RouteTable.Routes.GetVirtualPathForArea( Request.RequestContext, new RouteValueDictionary(new page=1 )).VirtualPath; 来获取当前的网址,使用新增路由值字典(RouteValueDictionary)的方式增加额外的路由值(即URL参数)
  • 直接获取RouteData内的值
  1. 在View内获取Route Value: @(ViewContext.RouteData.Values["action"]); @ViewContext.RouteData.Values["controller"];
  2. 在Controller内获取Route Value:
    var currentAction=RouteData.Values["action"];
    var currentController=RouteData.Values["controller"];
  3. 在类内获取Route Value(这里用到的时HtmlHelper)
    public static string GetCurruentControllerName(this HtmlHelper helper)
    { return (string)helper.ViewContext.RouteData.Values["controller"]; }
  • 如何调试网站
  1. 使用Route Debugger 2.0,它是属于项目等级的程序包,可以使用NuGet搜索Route Debugger 程序包并安装,可以查看当前网页匹配的具体路由;
  2. 使用Cobisi Routing Assitant Assistant,它是属于VS的扩展功能,此程序包已分析出整个项目内的网址路由,包括RouteConfig、Area、Attribute Routing,当然也可以使用Cobisi Routing Assistant->URl Mapper命令来测试网址的设置是否和预想的一样。
  • Area-提供了模块化的功能 主层与Area相互调用的方式: 当项目中创建了area之后,开发者最好在调用时加上area,如下:
@Html.ActionLink("前往AD页面""Index",//action名称
new {
 controller=""AD",//Controller名称
 area="Admin"//Area名称
})
<a href="@Url.Action("Index","AD",new {area="Admin"})">前往AD页面</a>

如果需要从area导向到主层的Controller,就没办法给予Area名称,而且MVC内建的机制会判断当前的Controller和Area,若没有给出,会默认使用当前的Area,若要回到主层就在Area名称指定空字符串即可:

@Html.ActionLink("前往主层About页面""About",new 
{
 controller="Home",area=""
}
)
<a href="@Url.Action("About","Home",new {area=""})">前往主层About页面</a>
posted @ 2017-09-24 12:50  tuohaibei  阅读(565)  评论(0编辑  收藏  举报