ASP.NET MVC中建立自訂路由約束

來源:互聯網
上載者:User

建立一個路由約束(C#)

你能夠使用路由約束來限制匹配一個特殊路徑的瀏覽器請求。你能夠使用一 個Regex來制定一個路由約束。

例如,假設你已經定義路由如下:

Listing 1 - Global.asax.cs

routes.MapRoute(

   "Product",

   "Product/{productId}",

   new {controller="Product", action="Details"}

);

Listing 1 包含一個命名為Product的路由. 你能夠使用這個 Product route來將將瀏覽器請求映射到ProductController,如下:

Listing 2 - Controllers\ProductController.cs

using System.Web.Mvc;

namespace MvcApplication1.Controllers

{

   public class ProductController : Controller

   {

       public ActionResult Details(int productId)

       {

           return View();

       }

   }

}

注意:Details() action 接收一個命名為 productId的單一參數. 這個參數是整型參數.

在 Listing 1 will中定義的route將匹配一下的任何一個URLs:

?/Product/23

?/Product/7

遺憾的 ,這個route也同樣匹配以下的URLs:

?/Product/blah

?/Product/apple

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.