MVC 框架 - 路由引擎

ASP.NET MVC 路由允许使用描述用户操作的 URL,使用户更容易理解。同时,路由可用于隐藏不打算显示给最终用户的数据。

例如,在未使用路由的应用程序中,将向用户显示 URL http://myapplication/Users.aspx?id=1,该 URL 对应于 myapplication 路径中的文件 Users.aspx,发送 ID 为 1,通常,我们不希望向最终用户显示此类文件名。

为了处理 MVC URL,ASP.NET 平台使用路由系统,它允许您创建所需的任何 URL 模式,并以清晰简洁的方式表达它们。MVC 中的每个路由都包含一个特定的 URL 模式。此 URL 模式与传入请求 URL 进行比较,如果 URL 与此模式匹配,则路由引擎将使用它来进一步处理请求。

MVC 路由 URL 格式

要了解 MVC 路由,请考虑以下 URL −

http://servername/Products/Phones

在上述 URL 中,Products 是第一段,Phone 是第二段,可以用以下格式表示 −

{controller}/{action}

MVC 框架自动将第一段视为控制器名称,将第二段视为该控制器内的操作之一。

注意 − 如果您的控制器名称是 ProductsController,则您只会在路由 URL 中提及 Products。 MVC 框架自动理解 Controller 后缀。

创建简单路由

路由在 App_Start 项目文件夹下的 RouteConfig.cs 文件中定义。

MVC Route Config

您将在此文件中看到以下代码 −

public class RouteConfig { 
   
   public static void RegisterRoutes(RouteCollection routes) { 
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
      
      routes.MapRoute( 
         name: "Default", 
         url: "{controller}/{action}/{id}", 
         defaults: new { controller = "Home", action = "Index", 
            id = UrlParameter.Optional } 
      ); 
   } 
} 

应用程序启动时,Global.ascx 会调用此 RegisterRoutes 方法。Global.ascx 下的 Application_Start 方法会调用此 MapRoute 函数,该函数会设置默认的 Controller 及其操作(Controller 类中的方法)。

要按照我们的示例修改上述默认映射,请更改以下代码行 −

defaults: new { controller = "Products", action = "Phones", id = UrlParameter.Optional }

此设置将选择 ProductsController 并调用其中的 Phone 方法。同样,如果您在 ProductsController 中有其他方法(例如 Electronics),则其 URL 将是 −

http://servername/Products/Electronics