鍍金池/ 教程/ C#/ ASP.Net MVC路由
ASP.Net MVC簡介
ASP.Net MVC過濾器
ASP.Net MVC視圖
ASP.Net MVC安全
ASP.Net MVC手腳架
ASP.Net MVC控制器
ASP.Net MVC與SQL Server數(shù)據(jù)庫操作
ASP.Net MVC NuGet包管理
ASP.Net MVC入門程序
ASP.Net MVC Razor
ASP.Net MVC Bootstrap
ASP.Net MVC單元測試
ASP.Net MVC動作
ASP.Net MVC模式
ASP.Net MVC選擇器
ASP.Net MVC開發(fā)環(huán)境配置
ASP.Net MVC生命周期
ASP.Net MVC模型綁定
ASP.Net MVC自托管(本地主機部署)
ASP.Net MVC驗證
ASP.Net MVC緩存
ASP.Net MVC數(shù)據(jù)模型
ASP.Net MVC路由
ASP.Net MVC教程
ASP.Net MVC助手
ASP.Net MVC數(shù)據(jù)注解
ASP.Net MVC Web API

ASP.Net MVC路由

路由是指向一個控制器的HTTP請求的過程,這個處理的功能是在System.Web.Routing中實現(xiàn)的。 這個程序集不是ASP.NET MVC的一部分。 它實際上是ASP.NET運行時的一部分,并且作為.NET 3.5 SP1正式發(fā)布。

System.Web.Routing由MVC框架使用,但也被ASP.NET動態(tài)數(shù)據(jù)使用。 MVC框架利用路由將請求引導至控制器。 Global.asax文件是應用程序的一部分,可在其中定義應用程序的路由。

這是在上一章創(chuàng)建的MVC應用程序(FirstMVCApp)中的Global.asax中的應用程序啟動事件的代碼。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace FirstMVCApp
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

以下是RouteConfig類的實現(xiàn),其中包含一個RegisterRoutes方法。

using System;
using System.Collections.Generic;
using System.Linq;

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace FirstMVCApp {
   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});
      }
   }
}

您將定義路由,這些路由將URL映射到特定的控制器操作。一個動作只是控制器上的一個方法。它也可以從URL中選擇參數(shù)并將它們作為參數(shù)傳遞給方法。

所以在應用程序中定義的這個路由是默認路由。從上面的代碼可以看出,當你看到一個URL以(something)/(something)/(something)的形式到達的時候,第一個是控制器的名稱,第二個是動作的名字,第三個是一個ID參數(shù)。

理解路由

MVC應用程序使用ASP.NET路由系統(tǒng),它決定URL如何映射到控制器和操作。

當Visual Studio創(chuàng)建MVC項目時,它會添加一些默認路由來啟動。 運行應用程序時,您將看到Visual Studio已將瀏覽器定向到端口56922。幾乎可以肯定地每次在瀏覽器請求的URL中看到不同的端口號,因為Visual Studio在創(chuàng)建項目時會分配一個隨機端口。

在最后一個例子中,我們添加了一個控制器:HomeController ,所以也可以請求任何下面的URL,它們將被定向到HomeController上的Index 操作。如下都是有效的URL -

http://localhost:56922/Home/
-- 或者 --
http://localhost:56922/Home/Index

當瀏覽器請求 http://mysite/http://mysite/Home 時,它會從HomeControllerIndex方法獲取輸出。

也可以通過更改瀏覽器中的URL來嘗試此操作。在這個例子中,它是http://localhost:56922/,除了端口可能不同。

如果將/Home/Home/Index追加到URL并按下“Enter”按鈕,將看到與MVC應用程序輸出相同的結果。

正如在這種情況下可以看到有一個名為HomeController的控制器,這個HomeController將成為MVC應用程序的起點。

Visual Studio為新項目創(chuàng)建的默認路由。但是如果想遵循自己的約定,那么將需要修改路由。

自定義約定

當然可以添加您自己的路由。如果不喜歡這些動作名稱,或有不同的ID參數(shù),又或者一般情況下網(wǎng)站的URL結構不同,則可以添加自己的路由項。

下面來看一個簡單的例子??紤]有一個包含進程列表的頁面,以下是將轉到流程頁面的代碼。

routes.MapRoute(
   "Process",
   "Process/{action}/{id}",
   defaults: new{
      controller = "Process", action = "List ", id = UrlParameter.Optional}
);

當客戶端請求進來并尋找具有Process/Action/Id的URL時,它們將會進入到Process控制器。這里可以使動作有點不太一樣,默認動作使用的是List而不是Index。

現(xiàn)在到達的請求看起來像localhosts/process。 路由引擎將使用這個路由配置來傳遞它,所以它將使用List作為的默認行為。

以下是完整的類實現(xiàn)。創(chuàng)建一個名稱為:MyRouteConfig 的類,參考代碼 -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace FirstMVCApp
{

    public class MyRouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
               "Process", "Process/{action}/{id}",
               defaults: new
               {
                   controller = "Process",
                   action = "List",
                   id =
                  UrlParameter.Optional
               });

            routes.MapRoute(
               name: "Home", url: "{controller}/{action}/{id}",
               defaults: new
               {
                   controller = "Home",
                   action = "Index",
                   id =
                  UrlParameter.Optional
               });
        }
    }
}

第1步 - 運行它并請求一個流程頁面,使用以下URL :http://localhost:63664/Process,應該會看到以下結果 -

將看到一個HTTP 404,因為路由引擎正在查找ProcessController,但是不可用。

第2步 - 通過右鍵單擊解決方案管理器 中的Controllers 文件夾來創(chuàng)建ProcessController,然后選擇:添加 -> 控制器 。

它將顯示“添加基架” 對話框。如下圖所示 -

第3步 - 選擇MVC 5控制器 - 空選項,然后單擊“添加” 按鈕。添加控制器對話框將出現(xiàn)。

第4步 - 將名稱設置為ProcessController,然后單擊“添加” 按鈕。如下圖所示 -

現(xiàn)在,將在Controllers文件夾中看到一個新的 C# 文件:ProcessController.cs,在Visual Studio中打開并進行編輯。如下圖所示 -

第5步 - 將返回類型從ActionResult更改為String,并使用以下代碼從此操作方法返回一些字符串。修改后的 ProcessController 文件中的代碼如下 -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FirstMVCApp.Controllers
{
    public class ProcessController : Controller
    {
        // GET: Process
        public String Index()
        {
            return "ProcessController.Index() Page.";
        }

        // GET: Process
        public String List()
        {
            return "ProcessController.List() Page.";
        }
    }
}

第6步 - 當運行這個應用程序,會看到默認路由的結果。當指定以下URL( http://localhost:56922/Process/List )時,您將看到ProcessController的結果。