ASP. net mvc 4 practices 10: routes (below ),

Source: Internet
Author: User

ASP. net mvc 4 practices 10: routes (below ),

6. Route debugging:

1. Install Route Debugger:

On the NuGet Package Manager Console, enter:

install-package routedebugger

2. Use Route Debugger:
Once Route Debugger is installed, the reference to RouteDebugger. dll is added to the project, and web. config also adds a new application setting:

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

Note: before deploying an application, make sure that the Route Debugger is disabled. Set RouteDebugger: Enabled to false.

Start debugging and go to the ProductsByCategory page. You can see:

The "Route Debugger" section displays the Route parameters that match the current request. The "Data Tokens" section displays any custom Data tags associated with the Route; the "All Routes" section displays True in the "Matches CurrentRequest" column to indicate which Routes may potentially match the current request, the first route for this column as True is the route selected to process the current request.

We changed the "ProductsByCategory" route:

            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" });

Then access/Products/ByCategory, and an error is returned:

We can see that there are several routes that match the/Products/ByCategory address, but the matching first route is "products". The user is taken to the product information page instead of the ProductsByCategory page.

3. Routing constraints:

In the above example, to prevent any input from matching the "productCode" segment of the "products" route, we can use a regular expression to limit what content can match this parameter:

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

In this example, we use a regular expression to exclude the string ByCategory. We can also use custom constraints to replace regular expressions:

Namespace RoutingSample {public class NotEqualConstraint: IRouteConstraint {private string _ input; public NotEqualConstraint (string input) {_ input = input;} public bool Match (HttpContextBase httpContext, // reference Route route in the HTTP context, // The constrained Route string parameterName, // The constrained route parameter name RouteValueDictionary values, // set the current route value RouteDirection routeDirection // specifies whether the route is used to match the input request or generate a 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")});

7. Test routing behavior: [I am dizzy again...]
1. Test the ingress:

1) Test the hard routing mode:
First introduce NUnit:

install-package nunit -version 2.6.3

Add test:

Namespace RoutingSample. Tests {[TestFixture] public class NotUsingTestHelper {[Test] public void root_matches_home_controller_index_action () {const string url = "~ /"; // Create an imitation request 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 (); // register the route RouteTable. routes. clear (); RouteConfig. registerRoutes (RouteTable. routes); var routeData = RouteTable. routes. getRouteData (context); // obtain the route Assert used for the request. that (routeData. values ["controller"], Is. failed to ("Home"); // Assert that the controller is correct. that (routeData. values ["action"], Is. failed to ("Index"); // The asserted action is correct }}}

2) use the MvcContrib Route Test extension:
First install the MvcContrib. TestHelper assembly:

install-package mvccontrib.mvc3.testhelper-ci

Add test:

[TestFixtureSetUp] public void FixtureSetup () {RouteTable. Routes. Clear (); RouteConfig. RegisterRoutes (RouteTable. Routes);} [Test] public void root_maps_to_home_index (){"~ /". ShouldMapTo <HomeController> (x => x. Index (); // assert that the URL is mapped to the action}

3) Test the routing example:

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 (); // assert that the URL is mapped to the action} [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. Test the outbound route:

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");        }    }}

Source code download password: mh5o

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.