[译]ASP.NET MVC动手实验1-2:创建ASP.NET MVC应用

任务5 – 理解 ASP.NET URL 路径

ASP.NET MVC 框架使用 ASP.NET 路径(ASP.NET Routing)进行 URLs 到控制器类和行为的映射。 ASP.NET 路径根据你定义的模式解析 URLs 中的变量,并自动将变量传递给控制器行为作为参数。通过这样的方式,URLs 不必映射到网站中特定的文件。

默认情形下, ASP.NET MVC 项目有一个预配置的 URL 路径映射规则, 使你可以轻松地开始你的应用开发而不用做任何明确的配置。你可以使用 ASP.NET MVC 项目模板自动为 ASP.NET 应用 创建的 Global.asax 文件中默认的基于名称的(name-based)的 URL 映射约定开始开发。

The preconfigured routing rule indicates that the ASP.NET MVC framework should by default map URLs to Controllers using a [controller]/[action]/[id] pattern when determining which Controller class to instantiate, and which Action method to invoke (along with which parameters should be passed in). 预配置的路径规则指示 ASP.NET MVC 框架在检测哪一个 控制器 类需要实例化以及哪一个 行为 方法应该被调用时(以及哪一些参数应该被传入)的时候,默认将 URLs 按照 [controller]/[action]/[id] 模式进行映射,

提示:在 解决方案浏览器 中双击 Global.asax,可以查看预配置的路径定义。

  1. 创建一个 MvcSampleApp 项目的新实例:在 解决方案浏览器 中右键点击 MvcSampleApp 项目,指向 调试 并选择 创建新实例。 提示:如果出现 未启用调试 对话框, 选择 修改Web.config文件以启用调试 并点击 确定。A request will be made to http://localhost:50000 which will be intercepted by the ASP.NET Routing engine applying the Default registered route (the pattern is [controller]/[action]/[id]). Since the URL does not contain any controller to map, the routing engine will instantiate a default controller (Home), and invoke a default action (Index) specified in the registered route.一个指向 http://localhost:50000 的请求将被创建,该请求将被 ASP.NET 路径 引擎拦截并应用在路径规则 ([controller]/[action]/[id] 模式)中注册的 Default 规则。一旦 URL 不包含任何指定的 Controller 映射, 路径引擎将实例化默认控制器(Home), 并调用默认的行为(Index)。
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default",                                              // Route name
        "{controller}/{action}/{id}",                           // URL with parameters
        new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
    );

}
[][5] 在此情形下,默认的路径参数为: 控制器 = Home, 行为 = Index; 因此 Home 控制器的 Index View 将被渲染呈现到浏览器中。 [<img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="//file.ofcdn.com/attachments/2009/04/image-thumb5.png" border="0" alt="image" width="581" height="411" />][7] *图五:MVC 示例应用的主页* 提示:默认 URL 路径模式就如之前指出的: **…/[ControllerName]/[Action]/[Parameters]**。你可以在 **Global.asax.cs** 文件中的 **RegisterRoutes** 方法下定义新的路径规则。 路径规则将通过 **Global.asax** 或者 **Global.asax.vb** 文件中的 **Application_Start** 方法初始化。

2. 点击页面右上角的 About 链接,浏览 About 页面。在浏览器中你可以看到地址重定向到 http://localhost:50000/Home/About,该地址调用了 Home 控制器 的 About 方法。image图六:About 页面

练习一到此就结束了。下次我们将进行 **练习二:开发 ASP.NET MVC 应用 **。

(文本翻译自 ASP.NET MVC Training Kit,下载地址:http://www.microsoft.com/downloads/details.aspx?FamilyID=1E0BE0B2-910A-4676-9F3A-41E4D9C0FC08&displaylang=en