ASP.NET MVC路由(四)
前言
在前面的篇幅中我们讲解路由系统在MVC中的运行过程以及粗略的原理,想必看过前面篇幅的朋友应该对路由有个概念***的了解了,本篇来讲解区域,在读完本篇后不会肯定的让你对区域有彻底的了解,但是会让你在以后对这部分知识掌握的路上夯上厚实的基础。
区域
在路由的起初在按照VS环境新建的MVC项目来讲的,今天区域也是按照这样的套路来讲。MSDN上说,在大型项目使用中被MVC划分为较小单元也就是区域,我没有使用过区域的经验,所以这篇只能讲解它的对象模型以及粗略的原理。
(没有MVC项目的新建一个)首先在MVC项目中,右键项目->添加->区域,然后在弹出的对话框中输入区域的名称,如图
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuYjN3YTO4QjN0IjMwATOw8CX2ADNxAjMvwFO4kzNyYzLcl2Lc12bj5yZvxmY0lmbj5ycldWYtl2Lc9CX6MHc0RHaiojIsJye.png)
点击添加后会发现在项目中出现这样的目录结构,如图:
暂时先不管这些目录结构的意思,先来看一下前面篇幅中说到的Global.asax文件中的MvcApplication类的Application_Start()方法中注册区域的代码:
1
<code>1 AreaRegistration.RegisterAllAreas();</code>
RegisterAllAreas()方法就是注册所有区域的意思,如图所示过程:
在RegisterAllAreas()方法执行的时候内部会根据MVC-AreaRegistrationTypeCache.xml区域缓存文件来读取所缓存的所有区域类型(全部是实现AreaRegistration),如果缓存文件中为空,则会遍历当前系统所依赖的所有程序集搜寻AreaRegistration类型且写入到缓存文件。
并且返回一个类型集合,此时的类型集合中都是实现了AreaRegistration类型的实现类,在遍历每一个类型的时候都会引用传递的把当前系统的路由表RouteTable.Routes传递到新建对象AreaRegistrationContext(参数上下文对象)中,随后再调用基类AreaRegistration的抽象方法RegisterArea(),当然了这是框架中才这么实现的,而在实际情况中此处的基类AreaRegistration已经是上述示例中的AreaCaseAreaRegistration类型了。
到这里我们看一下AreaCaseAreaRegistration类型的内部实现:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<code> </code><code>1 </code><code>public</code> <code>class</code> <code>AreaCaseAreaRegistration : AreaRegistration</code>
<code> </code><code>2 {</code>
<code> </code><code>3 </code><code>public</code> <code>override</code> <code>string</code> <code>AreaName</code>
<code> </code><code>4 {</code>
<code> </code><code>5 </code><code>get</code>
<code> </code><code>6 {</code>
<code> </code><code>7 </code><code>return</code> <code>"AreaCase"</code><code>;</code>
<code> </code><code>8 }</code>
<code> </code><code>9 }</code>
<code>10 </code>
<code>11 </code><code>public</code> <code>override</code> <code>void</code> <code>RegisterArea(AreaRegistrationContext context)</code>
<code>12 {</code>
<code>13 context.MapRoute(</code>
<code>14 </code><code>"AreaCase_default"</code><code>,</code>
<code>15 </code><code>"AreaCase/{controller}/{action}/{id}"</code><code>,</code>
<code>16 </code><code>new</code> <code>{ action = </code><code>"Index"</code><code>, id = UrlParameter.Optional }</code>
<code>17 );</code>
<code>18 }</code>
<code>19 }</code>
这里要说的是在RegisterArea()方法中的AreaRegistrationContext类型中的MapRoute()方法并不是RouteCollectionExtensions扩展类型中的方法,而是在此外面又包装了一层,此处的MapRoute()方法注册的路由对象中DataTokens属***值&rdquo; area&rdquo;索引下则是次路由所在的区域,也就是区域名称。
这个时候可以通过调试发现,区域中的路由也和程序中定义的路由一起被注册到了路由表中,说明区域也就是路由定义在物理文件上的划分,当然还有其它大的作用,本人暂时没有领悟到,有感了会第一时间和大家分享。
本文转自jinyuan0829 51CTO博客,原文链接:http://blog.51cto.com/jinyuan/1423999,如需转载请自行联系原作者