《ASP.NET MVC 4 實戰》學習筆記 10:路由(下)

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

六、調試路由:

1.安裝Route Debugger:

  在NuGet包管理器控制台輸入:

install-package routedebugger

2.使用Route Debugger:
  一旦安裝了Route Debugger對RouteDebugger.dll的引用便被添加到項目中,web.config也會添加一條新的應用程式設定:

<add key="RouteDebugger:Enabled" value="true" />

註:在部署應用程式之前要確保禁用了Route Debugger,即將RouteDebugger:Enabled設為false。

啟動調試,進入ProductsByCategory頁面,可以看到:

“Route Debugger”部分顯示了與當前請求匹配的路由參數;“Data Tokens”部分顯示了與該路由關聯在一起的任意自訂資料標記;“All Routes”部分通過在“Matches CurrentRequest”列顯示True表示哪些路由可能潛在地與當前請求匹配,該列為True的第一條路由是被選來處理當前請求的路由。

我們修改“ProductsByCategory”路由為:

            routes.MapPageRoute(                "ProductsByCategory",                "products/ByCategory/{category}",                "~/ProductsByCategory.aspx",                checkPhysicalUrlAccess: true,                defaults: new RouteValueDictionary(new { category = "All" }));            routes.MapRoute("404-catch-all", "{*catchall}", new { Controller = "Error", Action = "NotFound" });

然後訪問/Products/ByCategory,會報錯:

我們可以看到有好幾條與/Products/ByCategory地址匹配的路由,但匹配的第一條路由是“products”,使用者被帶到產品資訊頁而不是ProductsByCategory頁。

3.使用路由約束:

上例中為了不讓任何輸入都與“products”路由的“productCode”片段匹配,我們可以用一個Regex來限制什麼內容能與這一參數匹配:

            routes.MapRoute("product", "products/{productCode}/{action}",                            new { controller = "Catalog", action = "Show" },                            new { productCode="(?!ByCategory).*"});

此例我們使用Regex排除了字串ByCategory。我們也可以使用自訂約束來代替Regex:

namespace RoutingSample{    public class NotEqualConstraint : IRouteConstraint    {        private string _input;        public NotEqualConstraint(string input)        {            _input = input;        }        public bool Match(HttpContextBase httpContext, //HTTP內容相關的引用            Route route, //約束的路由            string parameterName, //被約束的路由參數名            RouteValueDictionary values, //當前路由值集合            RouteDirection routeDirection //指明該路由是用來匹配輸入請求還是用於產生URL            )        {            object matchingValue;            if (values.TryGetValue(parameterName, out matchingValue))            {                if (_input.Equals((string)matchingValue, StringComparison.OrdinalIgnoreCase))                {                    return false;                }            }            return true;        }    }}
            routes.MapRoute("product", "products/{productCode}/{action}",                            new { controller = "Catalog", action = "Show" },                            new {productCode=new NotEqualConstraint("ByCategory")});

七、測試路由行為:[我又暈了。。。]
1.測試入站路由:

1)測試路由的硬方式:
  首先引入NUnit:

install-package nunit -version 2.6.3

   添加測試:

namespace RoutingSample.Tests{    [TestFixture]    public class NotUsingTestHelper    {        [Test]        public void root_matches_home_controller_index_action()        {            const string url = "~/";            // 建立模仿請求            var request = MockRepository.GenerateStub<HttpRequestBase>();            request.Stub(x => x.AppRelativeCurrentExecutionFilePath)                .Return(url).Repeat.Any();            request.Stub(x => x.PathInfo)                .Return(string.Empty).Repeat.Any();            var context = MockRepository                .GenerateStub<HttpContextBase>();            context.Stub(x => x.Request)                .Return(request).Repeat.Any();            // 註冊路由            RouteTable.Routes.Clear();            RouteConfig.RegisterRoutes(RouteTable.Routes);                        var routeData = RouteTable.Routes.GetRouteData(context);// 擷取用於請求的路由            Assert.That(routeData.Values["controller"], Is.EqualTo("Home"));// 斷言控制器正確            Assert.That(routeData.Values["action"], Is.EqualTo("Index")); //斷言動作正確        }    }}

2)使用MvcContrib的路由測試擴充:
  首先安裝MvcContrib.TestHelper程式集:

install-package mvccontrib.mvc3.testhelper-ci

  添加測試:

        [TestFixtureSetUp]        public void FixtureSetup()        {            RouteTable.Routes.Clear();            RouteConfig.RegisterRoutes(RouteTable.Routes);        }        [Test]        public void root_maps_to_home_index()        {            "~/".ShouldMapTo<HomeController>(x => x.Index());// 斷言URL映射到動作        }

3)測試樣本路由:

namespace RoutingSample.Tests{    [TestFixture]    public class UsingTestHelper    {        [TestFixtureSetUp]        public void FixtureSetup()        {            RouteTable.Routes.Clear();            RouteConfig.RegisterRoutes(RouteTable.Routes);        }        [Test]        public void root_maps_to_home_index()        {            "~/".ShouldMapTo<HomeController>(x => x.Index());// 斷言URL映射到動作        }        [Test]        public void privacy_should_map_to_home_privacy()        {            "~/privacy".ShouldMapTo<HomeController>(x => x.Privacy());        }        [Test]        public void products_should_map_to_catalog_index()        {            "~/products".ShouldMapTo<CatalogController>(x => x.Index());        }        [Test]        public void product_code_url()        {            "~/products/product-1".ShouldMapTo<CatalogController>(x => x.Show("product-1"));        }        [Test]        public void product_buy_url()        {            "~/products/product-1/buy".ShouldMapTo<CatalogController>(x => x.Buy("product-1"));        }        [Test]        public void basket_should_map_to_catalog_basket()        {            "~/basket".ShouldMapTo<CatalogController>(x => x.Basket());        }        [Test]        public void checkout_should_map_to_catalog_checkout()        {            "~/checkout".ShouldMapTo<CatalogController>(x => x.CheckOut());        }        [Test]        public void _404_should_map_to_error_notfound()        {            "~/404".ShouldMapTo<ErrorController>(x => x.NotFound());        }        [Test]        public void ProductsByCategory_MapsToWebFormPage()        {            "~/Products/ByCategory".ShouldMapToPage("~/ProductsByCategory.aspx");        }    }}

2.測試出站路由:

namespace RoutingSample.Tests{    [TestFixture]    public class OutboundUrlTests    {        [TestFixtureSetUp]        public void FixtureSetup()        {            RouteTable.Routes.Clear();            RouteConfig.RegisterRoutes(RouteTable.Routes);        }        [Test]        public void Generate_home_url()        {            OutBoundUrl.Of<HomeController>(x => x.Index())                .ShouldMapToUrl("/");        }        [Test]        public void Generates_products_url()        {            OutBoundUrl.Of<CatalogController>(x => x.Show("my-product-code"))                .ShouldMapToUrl("/products/my-product-code");        }    }}

源碼下載 密碼:mh5o

《ASP.NET MVC 4 實戰》學習筆記 10:路由(下)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.