URL routing Overview

Source: Internet
Author: User
ArticleDirectory
    • Use the default route table
    • Create a custom route
URL routing Overview

In this tutorial, we will introduceProgramAre very importantURL RoutingFunction. The URL routing model maps browser requests to specific MVC controllers.

In the first part of this tutorial, we will learn how the standard route table maps requests to controllers. In the second part of this tutorial, we will learn how to use custom routes to modify the default route table.

Use the default route table

When creating a new ASP. net mvc application, the application has configured the use of URL routing. URL routing is set in two locations.

First, the URL is routed to the Web configuration file of the application (Web. configFile. There are four parts in the configuration file related to routing:System. Web. httpmodulesPart,System. Web. httphandlersPart,System. webserver. ModulesParts andSystem. webserver. handlers. Do not delete these parts, because they cannot work without routing.

Second, but the more important position is to create a route table in the ApplicationGlobal. asaxFile.Global. asaxA file is a special file that contains Event Handlers for ASP. NET application lifecycle events. The route table is created in the Application Start event.

The files in program list 1 contain the default values of ASP. net mvc applications.Global. asaxFile.

Program list 1Global. asax. CS


  
  
  1. UsingSystem;
  2. UsingSystem. Collections. Generic;
  3. UsingSystem. LINQ;
  4. UsingSystem. Web;
  5. UsingSystem. Web. MVC;
  6. UsingSystem. Web. Routing;
  7.  
  8. NamespaceMyApp
  9. {
  10. Public ClassGlobalapplication: system. Web. httpapplication
  11. {
  12. Public Static VoidRegisterroutes (routecollection routes)
  13. {
  14. Routes. ignoreroute ("{Resource}. axd/{* pathinfo }");
  15. Routes. maproute (
  16. "Default",// Route name
  17. "{Controller}/{action}/{ID }",// URL with Parameters
  18. New{Controller ="Home", Action ="Index", Id =""}
  19. // Parameter defaults );
  20. }
  21.  
  22. Protected VoidApplication_start ()
  23. {
  24. Registerroutes (routetable. routes );
  25. }
  26. }
  27. }

When the ASP. NET application is started for the first timeApplication_start ()Method. This method will callRegisterroutes ()Method.Registerroutes ()Method To create a route table.

The default route table contains a route (named default ). The default route maps the first segment of the URL to the Controller name, the second segment to the Controller operation, and the third segment toID.

Assume that the following URL is entered in the address bar of the Web browser:

/Home/index/3

The default route maps the URL to the following parameters:

Controller = home

Action = index

Id = 3

When you request URL/home/index/3, execute the followingCode:

Homecontroller. Index (3)

The default route includes the default values of three parameters. If no controller is provided, the default value of the controller parameter isHome. If no operation is provided, the default value of the operation parameter isIndex. Finally, if no ID is provided, the ID parameter is a null string by default.

Let's look at several examples to learn how the default route maps URLs to Controller operations. Assume that the following URL is entered in the address bar of the Web browser:

/Home

Because of the default value of the default route parameter, entering this URL will cause the callerHomecontrollerClassIndex ()Method.

Program list 2Homecontroller. CS


  
  
  1. UsingSystem;
  2. UsingSystem. Collections. Generic;
  3. UsingSystem. LINQ;
  4. UsingSystem. Web;
  5. UsingSystem. Web. MVC;
  6.  
  7. NamespaceMyApp. Controllers
  8. {
  9. [Handleerror]
  10. Public ClassHomecontroller: Controller
  11. {
  12. PublicActionresult index (StringID)
  13. {
  14. ReturnView ();
  15. }
  16. }
  17. }

In program list 2,HomecontrollerThe class name isIndex ()This method accepts a parameter named ID. URL/home causes the call to have a Null StringIndex ()Method as the value of the ID parameter.

Because ASP. net mvc Framework activates controller operations, URL/home can also matchHomecontrollerClassIndex ()Method.

Program list 3Homecontroller. CS(Index operation without parameters)


  
  
  1. UsingSystem;
  2. UsingSystem. Collections. Generic;
  3. UsingSystem. LINQ;
  4. UsingSystem. Web;
  5. UsingSystem. Web. MVC;
  6.  
  7. NamespaceMyApp. Controllers
  8. {
  9. [Handleerror]
  10. Public ClassHomecontroller: Controller
  11. {
  12. PublicActionresult index ()
  13. {
  14. ReturnView ();
  15. }
  16. }
  17. }

In program list 3Index ()The method does not accept any parameters. URL/home will cause the callIndex ()Method. URL/home/index/3 also activates this method (ignore ID ).

URL/home can also matchHomecontrollerClassIndex ()Method.

Program list 4Homecontroller. CS(Index operation with parameters that can be left blank)


  
  
  1. UsingSystem;
  2. UsingSystem. Collections. Generic;
  3. UsingSystem. LINQ;
  4. UsingSystem. Web;
  5. UsingSystem. Web. MVC;
  6.  
  7. NamespaceMyApp. Controllers
  8. {
  9. [Handleerror]
  10. Public ClassHomecontroller: Controller
  11. {
  12. PublicActionresult index (Int? ID)
  13. {
  14. ReturnView ();
  15. }
  16. }
  17. }

In program list 4,Index ()The method has an integer parameter. Because the parameter can be blank (the value can be nothing), it can be called without causing an error.Index ().

Finally, use URL/home to activateIndex ()Method will cause an exception because the ID ParameterNoCan be null. If you try to activateIndex ()Method, the error page shown in 1 is displayed.

Program list 5Homecontroller. CS(Index operation with ID parameter)


  
  
  1. UsingSystem;
  2. UsingSystem. Collections. Generic;
  3. UsingSystem. LINQ;
  4. UsingSystem. Web;
  5. UsingSystem. Web. MVC;
  6.  
  7. NamespaceMyApp. Controllers
  8. {
  9. [Handleerror]
  10. Public ClassHomecontroller: Controller
  11. {
  12. PublicActionresult index (IntID)
  13. {
  14. ReturnView ();
  15. }
  16. }
  17. }

Figure 1: Activate the Controller operation that requires parameter values (click to view the large image)

On the other hand, URL/home/index/3 can work with the index controller operation in listing 5. Request/home/index/3 leads to the call of the ID parameter with a value of 3Index ()Method.

Create a custom route

For many simple ASP. net mvc applications, you can use the default route table. However, you may have special routing requirements. In this case, you should create a custom route.

For example, if you are creating a blog application. The following request must be processed:

/Archive/12-25-2009

When you enter this request, you want to return a blog entry with a date of 12/25/2009. To process such requests, you must create a custom route.

In program list 6Global. asaxThe file contains a new custom Route namedBlog, Which is processed in the form of/archive/Entry date.

Program list 6Global. asax(Use custom Routing)


  
  
  1. UsingSystem. Web. MVC;
  2. UsingSystem. Web. Routing;
  3.  
  4. NamespaceMyApp
  5. {
  6. Public ClassGlobalapplication: system. Web. httpapplication
  7. {
  8. Public Static VoidRegisterroutes (routecollection routes)
  9. {
  10. Routes. ignoreroute ("{Resource}. axd/{* pathinfo }");
  11. Routes. maproute (
  12. "Blog",
  13. "Archive/{entrydate }",
  14. New{Controller ="ARCHIVE", Action ="Entry"}
  15. );
  16. Routes. maproute (
  17. "Default",// Route name
  18. "{Controller}/{action}/{ID }",// URL with Parameters
  19. New{Controller ="Home", Action ="Index", Id =""}
  20. // Parameter defaults );
  21. }
  22.  
  23. Protected VoidApplication_start ()
  24. {
  25. Registerroutes (routetable. routes );
  26. }
  27. }
  28. }

The order in which route entries are added to a route table is very important. New CustomBlogAdd a route before the existing default route. If the order is the opposite, the default route is always called instead of the custom route.

CustomBlogThe route matches any request starting with/archive. Therefore, it matches all the following urls:

/Archive/12-25-2009

/Archive/10-6-2004

/Archive/Apple

Custom route maps incoming requests toArchiveController and activateEntry ()Operation. WhenEntry ()Method, the entry date will be passed as the parameter named entrydate.

You can setBlogCustom routing is used on the Controller in program listing 7.

Procedure 7Archivecontroller. CS


  
  
  1. UsingSystem;
  2. UsingSystem. Web. MVC;
  3.  
  4. NamespaceMyApp. Controllers
  5. {
  6. Public ClassArchivecontroller: Controller
  7. {
  8. Public StringEntry (datetime entrydate)
  9. {
  10. Return "You requested the entry on"+ Entrydate. tostring ();
  11. }
  12. }
  13. }

Note thatEntry ()Method acceptanceDatetimeType parameter. ASP. net mvc Framework intelligently converts the entry date in a URLDatetimeValue. If you cannot convert the entry date in the URLDatetimeThe error message is displayed.

Summary

The purpose of this tutorial is to brief youURL Routing. First, we have studied the default route table in the new ASP. net mvc application. Learn how default routes map URLs to controllers.

Next, we learned how to create a custom route. Learned how to express a blog entryGlobal. asaxFile to add a custom route. We discussed how to map requests to blog entriesArchivecontrollerThe Controller and nameEntry ().

Http://msdn.microsoft.com/zh-cn/dd320290

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.