"ASP 4 Combat" Learning Note 10: Routing (bottom)

Source: Internet
Author: User

Six, Debug routing:

1. Install route Debugger:

In the NuGet Package Manager console, enter:

Install-package Routedebugger

2. Use route Debugger:
Once the route debugger is installed, a reference to RouteDebugger.dll is added to the project, and Web. config adds a new application setting:

<key= "routedebugger:enabled"  value= "true"/>

Note: Be sure to disable Route Debugger and set routedebugger:enabled to False before deploying the application.

To start debugging, go to the Productsbycategory page and see:

The "Route Debugger" section shows the route parameters that match the current request, and the "Data Tokens" section shows any custom data tags associated with the route, and the "All Routes" section is passed in the "Matches currentrequest" The column display true indicates which routes may potentially match the current request, and the first route that is true is selected to handle the route of the current request.

We modified the "productsbycategory" route to:

routes. Mappageroute ("productsbycategory",                "Products/bycategory/{category}",                "~/productsbycategory.aspx", checkphysicalurlaccess:true, defaults:NewRouteValueDictionary (New{category =" All" })); Routes. MapRoute ("404-catch-all","{*catchall}",New{Controller ="Error", Action ="NotFound"});

Then visit/products/bycategory, will error:

We can see several routes that match the/products/bycategory address, but the first route to match is "products", and the user is taken to the product information page instead of the Productsbycategory page.

3. Use Routing constraints:

In the above example, in order not to allow any input to match the "ProductCode" fragment of the "products" route, we can use a regular expression to limit what can match this parameter:

            Routes. MapRoute ("product""products/{productcode}/{action}",                             New " Catalog " " Show " },                            new {productcode="(?! bycategory). *"});

In this example we use regular expressions to exclude string bycategory. We can also use custom constraints instead of regular expressions:

namespaceroutingsample{ Public classNotequalconstraint:irouteconstraint {Private string_input;  PublicNotequalconstraint (stringinput) {_input=input; }         Public BOOLMatch (HttpContextBase HttpContext,//references to HTTP contextsRoute route,//constrained Routing            stringParameterName,//constrained route parameter nameRouteValueDictionary values,//Current route value CollectionRoutedirection routedirection//Indicates whether the route is used to match an input request or to generate a URL            )        {            ObjectMatchingvalue; if(values.) TryGetValue (ParameterName, outmatchingvalue)) {                if(_input. Equals ((string) (Matchingvalue, stringcomparison.ordinalignorecase)) {return false; }            }            return true; }    }}
 routes. MapRoute ( product  , "  products                            /{productcode}/{action}    new  {controller =  " catalog  , action = "  show    
           {productcode=new  Notequalconstraint (  " bycategory  )}); 

vii. Test routing behavior: [I was dizzy again ... ]
1. Test the inbound route:

1) test the hard way of routing:
First introduce NUnit:

2.6. 3

To add a test:

namespaceroutingsample.tests{[Testfixture] Public classNotusingtesthelper {[Test] Public voidroot_matches_home_controller_index_action () {Const stringURL ="~/"; //Create a mock request            varRequest = Mockrepository.generatestub(); Request. Stub (x=X.apprelativecurrentexecutionfilepath). Return (URL).            Repeat.any (); Request. Stub (x=x.pathinfo). Return (string. Empty).            Repeat.any (); varContext =mockrepository. Generatestub<HttpContextBase>(); Context. Stub (x=x.request). Return (Request).            Repeat.any (); //Registering RoutesRouteTable.Routes.Clear ();                        Routeconfig.registerroutes (routetable.routes); varRoutedata = RouteTable.Routes.GetRouteData (context);//gets the route used for the requestAssert.that (routedata.values["Controller"], Is.equalto ("Home"));//assert that the controller is correctAssert.that (routedata.values["Action"], Is.equalto ("Index"));//assertion action is correct        }    }}

2) Use the Mvccontrib Routing test extension:
Install the Mvccontrib.testhelper assembly first:

Install-package Mvccontrib.mvc3.testhelper-ci

To add a test:

        [Testfixturesetup]        publicvoid  fixturesetup ()        {            RouteTable.Routes.Clear ();            Routeconfig.registerroutes (routetable.routes);        }        [Test]          Public void Root_maps_to_home_index ()        {            "~/". shouldmapto// assert URL mapping to action        }

3) test the sample route:

namespaceroutingsample.tests{[Testfixture] Public classUsingtesthelper {[Testfixturesetup] Public voidFixturesetup () {RouteTable.Routes.Clear ();        Routeconfig.registerroutes (routetable.routes); } [Test] Public voidRoot_maps_to_home_index () {"~/". shouldmapto//Assertion URL mapping to action} [Test] Public voidprivacy_should_map_to_home_privacy () {"~/privacy". shouldmaptox.privacy ()); } [Test] Public voidProducts_should_map_to_catalog_index () {"~/products". shouldmapto<catalogcontroller> (x =X.index ()); } [Test] Public voidProduct_code_url () {"~/products/product-1". shouldmapto<catalogcontroller> (x = X.show ("product-1")); } [Test] Public voidProduct_buy_url () {"~/products/product-1/buy". shouldmapto<catalogcontroller> (x = X.buy ("product-1")); } [Test] Public voidBasket_should_map_to_catalog_basket () {"~/basket". shouldmapto<catalogcontroller> (x =X.basket ()); } [Test] Public voidcheckout_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 voidProductsbycategory_mapstowebformpage () {"~/products/bycategory". Shouldmaptopage ("~/productsbycategory.aspx"); }    }}

2. Test the outbound route:

namespaceroutingsample.tests{[Testfixture] Public classoutboundurltests {[Testfixturesetup] Public voidFixturesetup () {RouteTable.Routes.Clear ();        Routeconfig.registerroutes (routetable.routes); } [Test] Public voidGenerate_home_url () {Outboundurl.of<HomeController> (x =X.index ()). Shouldmaptourl ("/"); } [Test] Public voidGenerates_products_url () {Outboundurl.of<CatalogController> (x = X.show ("My-product-code"))                . Shouldmaptourl ("/products/my-product-code"); }    }}

Code Download Password: mh5o

"ASP 4 Combat" Learning Note 10: Routing (bottom)

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.