共用方式為


建立路由條件約束 (C#)

作者:Stephen Walther

在此教學課程中,Stephen Walther 示範如何使用規則運算式建立路由條件約束來控制瀏覽器要求如何比對路由。

您可以使用路由條件約束來限制符合特定路由的瀏覽器要求。 您可以使用規則運算式來指定路由條件約束。

例如,假設您已在 Global.asax 檔案的清單 1 中定義路由。

清單 1 - Global.asax.cs

routes.MapRoute(
    "Product",
    "Product/{productId}",
    new {controller="Product", action="Details"}
);

清單 1 包含名為 Product 的路由。 您可以使用 Product 路由,將瀏覽器要求對應至清單 2 中包含的 ProductController。

清單1 - Controllers\ProductController.cs

using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
    public class ProductController : Controller
    {
        public ActionResult Details(int productId)
        {
            return View();
        }
    }
}

請注意,Product 控制器所公開的 Details() 動作接受名為 productId 的單一參數。 這個參數是整數參數。

清單 1 中定義的路由將會符合下列任何 URL:

  • /Product/23
  • /Product/7

遺憾的是,路由也會符合下列 URL:

  • /Product/blah
  • /Product/apple

因為 Details() 動作需要整數參數,因此提出包含整數值以外的內容的要求將會造成錯誤。 例如,如果您在瀏覽器中輸入 URL /Product/apple,則會在圖 1 中取得錯誤頁面。

[New Project] \(新增專案\) 對話方塊

圖 01:查看頁面分解 (按一下以檢視全尺寸影像)

您真正想要做的只是比對包含適當整數 productId 的 URL。 您可以在定義路由時使用條件約束來限制符合路由的 URL。 清單 3 中修改過的 Product 路由包含只符合整數的規則運算式條件約束。

清單 3 - Global.asax.cs

routes.MapRoute(
    "Product",
    "Product/{productId}",
    new {controller="Product", action="Details"},
    new {productId = @"\d+" }
 );

規則運算式 \d+ 會比對一或多個整數。 此條件約束會使 Product 路由符合下列 URL:

  • /Product/3
  • /Product/8999

但不是下列 URL:

  • /Product/apple

  • /Product

  • 這些瀏覽器要求將由另一個路由處理,或者,如果沒有相符的路由,則會傳回找不到資源錯誤。