Detailed introduction to ASP. NET mvc--Routing

Source: Internet
Author: User
Tags what is asp

Understanding the default Routing table

When you create a new ASP. NET MVC application, the application is configured to use ASP. ASP. NET routing is set in two places.

1th, Enabling ASP. In your application's Web configuration file (Web. config file), there are four nodes in the configuration file that are related to routing: Sytem.web.httpModules section, system.web.httpHandlers section, System.webser Ver.modules Festival, and the System.webserver.handlers festival. In particular, be careful not to remove these nodes, because without them the route will not work.

2nd, and more importantly, a routing table is created in the Global.asax file in the application. The Global.asax file is a special file that contains event handlers that act on the ASP. NET application life cycle events. The routing table is created during application start events.

The file in code Listing 1 contains the default Global.asax file for an ASP. NET MVC application.

Code Listing 1-global.asax.cs

Use the system; Use System.Collections.Generic; Use System.Linq; Use system.web; Use SYSTEM.WEB.MVC; Use System.Web.Routing; namespace mvcapplication1{//Note: For instructions on enabling IIS6 or IIS7 Classic mode, go to http://go.microsoft.com/? linkid=9394801 public class MvcApplication:System.Web.HttpApplication {public static void RegisterRoutes (Ro Utecollection route) {routes.             Ignoreroute ("{resource}. Axd/{* PathInfo}");                Route.  MapRoute ("Default",//Route name "{Controller}/{action}/            {ID} ",//url with parameter new {controller =" Home ", action =" Index ", id =" "}//parameter default value         );         } protected void Application_Start () {registerroutes (routetable.routes); }}}//url with parameter new {controller = "Home", action = "Index", id = ""}//parameter defaults); } protected void Application_Start () {registerroutes (routetable.routes);}}} The URL with the parameter, new {controller = "HoMe ", action =" Index ", id =" "}//parameter defaults); } protected void Application_Start () {registerroutes (routetable.routes);}}} } protected void Application_Start () {registerroutes (routetable.routes);}}} } protected void Application_Start () {registerroutes (routetable.routes);}}}

The Application_Start () method is called when an MVC application runs for the first time. This method then calls the RegisterRoutes () method. The RegisterRoutes () method creates the route table.

The default routing table contains a route (called default). The default route maps the first part of the URL to the controller name, the second part of the URL maps to the controller action, and the third part maps to a parameter called ID.

Suppose you entered the following URL in the address bar of the browser:

/home/Index/3

The default route maps this URL to the following parameter:

Controller = Home

Action = Index

ID = 3

When you request the URL/home/index/3 o'clock, the following code will be executed:

Homecontroller.index (3)

The default route contains the default values for all three parameters. If you do not provide a controller, then the controller parameter defaults to the first page. If you do not provide an action, the action parameter defaults to the value indicator. Finally, if you do not provide the Id,id parameter, the default is an empty string.

Let's take a look at a few examples of how the default route maps URLs to controller actions. You entered the following URL in the browser address bar:

/home

Due to the default value of the default route parameter, entering this URL will invoke the exponential () method of the HomeController class in Listing 2.

Code Listing 2-homecontroller.cs

Use SYSTEM.WEB.MVC; namespace Mvcapplication1.controllers {     [HandleError] public     class Homecontroller:controller     {         public ActionResult Index (string id)        {             return View ();}}     }

In Listing 2, the HomeController class contains a method called index () that accepts a parameter called an ID. Url/home will cause the index () method to be called and the empty string to be the value of the ID parameter.

Url/home also matches the index () method of the HomeController class in code Listing 3 for the way that the MVC framework invokes the controller action.

Code Listing 3-homecontroller.cs (index action with no parameters)

Use SYSTEM.WEB.MVC; namespace Mvcapplication1.controllers {     [HandleError] public     class Homecontroller:controller     {         public ActionResult Index ()        {             return View ();}}     }

The index () method in code listing 3 does not accept any arguments. Url/home will cause the index () method to be called. URL/HOME/INDEX/3 also calls this method (ID is ignored).

Url/home also matches the index () method of the HomeController class in code Listing 4.

Code Listing 4-homecontroller.cs (index action with nullable parameters)

Use SYSTEM.WEB.MVC; namespace Mvcapplication1.controllers {     [HandleError] public     class Homecontroller:controller     {         public ActionResult Index (int?) ID)        {             return View ();}}     }

In code Listing 4, the index () method has an integer parameter. Because this parameter is a nullable parameter (which can have a null value), the exponent () can be called without raising an error.

Finally, using Url/home to invoke the index () method in Listing 5 throws an exception because the ID parameter is not a nullable parameter. If you try to invoke the index () method, you will get an error as shown in Figure 1.

Code Listing 5-homecontroller.cs (index action with ID parameter)

Use SYSTEM.WEB.MVC; namespace Mvcapplication1.controllers {     [HandleError] public     class Homecontroller:controller     {         public ActionResult Index (int id)        {             return View ();}}     }

Figure 01: A controller action that invokes an expected parameter value

On the other hand, URL/HOME/INDEX/3 is able to work well with the Index controller action in Listing 5. The/HOME/INDEX/3 request throws an index () method that contains an ID, and the ID value is 3.

The purpose of this tutorial is to provide you with a brief introduction to the ASP. We carefully reviewed the default routing table, which was obtained when you created a new ASP. NET MVC application. You learned how the default routing table maps URLs to controller actions.

2. Creating a custom route

In this tutorial, you will learn how to add a custom route for an ASP. NET MVC application. You will learn how to modify the default routing table in the Global.asax file to a custom route.

For a simple ASP. NET MVC application, the default routing table is ready to do the work well. However, you can find that there are specific routing requirements in this case, you can create a custom route.

Imagine, for example, that you are creating a blog application that you might want to handle the upcoming requests like this:

/archived/December 25, 2009

When the user enters this request, you want to return a blog entry that corresponds to the date December 25, 2009. In order to handle this type of request, you need to create a custom route.

The Global.asax in Listing 1 contains a new custom route named for the blog, which handles requests like/Archive/entry dates.

Code Listing 1-global.asax (contains custom routes)

Use SYSTEM.WEB.MVC; Use System.Web.Routing; Namespace MvcApplication1 {public class MvcApplication:System.Web.HttpApplication {public static void Registe Rroutes (RouteCollection routes) {routes.             Ignoreroute ("{resource}. Axd/{* PathInfo}"); Routes.                            MapRoute ("Blog",//Route name "Archive/{entrydate}",             URL with parameter new {controller = "Archive", action = "}//parameter defaults); Routes. MapRoute ("Default",///route name "{Controller}/{action}/{ID}",//url with parameter new {         Controller = "Home", action = "Index", id = ""}//parameter defaults);         } protected void Application_Start () {registerroutes (routetable.routes); }}}}//parameter defaults); Routes. MapRoute ("Default",///route name "{Controller}/{action}/{ID}",//url with parameter new {controller = "Home", action ="Index", id = ""}//parameter defaults); } protected void Application_Start () {registerroutes (routetable.routes);}} },///route name "{Controller}/{action}/{ID}",//url with parameter new {controller = "Home", action = "Index", id = ""}//parameter defaults); } protected void Application_Start () {registerroutes (routetable.routes);}} },//route name "{Controller}/{action}/{ID}",//with parameter URL New {controller = "Home", action = "Index", id = ""}//parameter defaults); } protected void Application_Start () {registerroutes (routetable.routes);}} }//URL with parameter new {controller = "Home", action = "Index", id = ""}//parameter defaults); } protected void Application_Start () {registerroutes (routetable.routes);}} }//URL with parameter new {controller = "Home", action = "Index", id = ""}//parameter defaults); } protected void Application_Start () {registerroutes (routetable.routes);}} }

The routing order that is added to the routing table is important. Our new custom blog route is preceded by the existing default route. If you reverse this order, the default route will always be called instead of the custom route.

Custom Blog Routing matches any request to/archive/as a start so it matches all of the following URLs:

/archived/December 25, 2009

/archived/October 6, 2004

/Archive/Apple

The custom route maps the incoming request to the Controller named Archive and invokes the entry () action. When the item () method is called, the entry date is passed as the EntryDate parameter.

Code Listing 2-archivecontroller.cs

Use the system; Use SYSTEM.WEB.MVC; namespace mvcapplication1.controllers{public    class Archivecontroller:controller    {public        string Entry (DateTime entrydate)        {            return "you have requested an entry from" + entrydate.tostring ()).        }    }}

Notice that the entry () method in Listing 2 takes a parameter of a datetime type. The MVC framework is smart enough to automatically convert entry dates in URLs to datetime values. If the entry date parameter in the URL cannot be converted to a datetime, an error (1) will be thrown.

Figure 1-Error when converting a parameter

The purpose of this tutorial is to demonstrate how to create a custom route. You learned how to add a custom route to the routing table of a file in Global.asax that represents a blog entry. We discussed how to map a request for a blog entry to a controller named Archivecontroller, and a controller action named item ().

3. Create a Routing constraint

You can use routing constraints to restrict browser requests that match a particular route. You can use a regular expression to specify a routing constraint.

For example, suppose you have defined a route in a file in Global.asax.

Code Listing 1-global.asax.cs

Routes. MapRoute (    "Product",    "product/{productId}",    new {controller = "Product", action = "Details"});

The Code Listing 1 contains a route called a product. You can use product routing to map browser requests to Productcontroller in code Listing 2.

Code Listing 2-controllers \ ProductController.cs

Use SYSTEM.WEB.MVC; namespace Mvcapplication1.controllers {public     class Productcontroller:controller     {public         ActionResult Details (int productId)        {             return View ();}}     }

Note that the details of the product Controller announcement () action accepts a parameter called ProductID. This parameter is an integer parameter.

The route defined in Code Listing 1 will match any of the following URLs:

/Products/23/products/7 Unfortunately, the route will also match the following URLs:/products/TA/products/Apple

Because the detailed () action expects an integer value, initiating a request with a non-integer value will result in an error. For example, if you enter/product/Apple URL in a browser, you will get the error page shown in Figure 1.

Figure 1: Error page

What you actually want to do is match only URLs that contain the appropriate integer productid parameter. You can use constraints when defining a URL where the route is restricted to match the routing. The modified product route in Code 3 contains a regular expression that restricts matching numbers only.

Code Listing 3-global.asax.cs

Routes. MapRoute (    "Product",    "product/{productId}",    new {controller = "Product", action = "Details"},    new { ProductId = @ "\ D +"}  )

Regular expression \ D + matches one or more integers this restriction makes the product route match the following URL:

/product/3/product/8999 but not match the following URL:/products/Apple/Products

These browser requests will be free of additional routes, or, if there is no matching route, a "resource not found" error will be returned.

Create a custom route constraint

The goal of this tutorial is to demonstrate how to create a custom routing constraint. Custom routing constraints allow you to prevent a path from being matched unless some custom conditions are met.

In this tutorial, we created a local host routing constraint. The localhost routing constraint matches only requests made by the local computer. Remote requests made over the Internet will not be matched.

。 You can implement a custom route by implementing the Irouteconstraint interface This is an extremely simple interface that describes only one method:

BOOL Match (    httpcontextbase HttpContext,    Route route,    string parametername,    routevaluedictionary value,    routedirection routedirection)

This method returns a Boolean value. If False is returned, the route associated with the constraint will not match the browser request.

The local host constraints are included in Listing 1.

Code Listing 1-localhostconstraint.cs

Use system.web; Use System.Web.Routing; namespace Mvcapplication1.constraints {public     class Localhostconstraint:irouteconstraint     {public         bool Match             (                HttpContextBase HttpContext,                Route route,                string parametername,                routevaluedictionary values,                Routedirection routedirection             )        {             return httpContext.Request.IsLocal;}}     }

The constraints in Listing 1 take advantage of the Islocal property of the HttpRequest class advertisement. This property returns True when the requested IP address is 127.0.0.1 or the IP address of the server is the same.

You used a custom constraint in the route defined in Global.asax. The files in Global.asax in Listing 2 use local host constraints to prevent anyone from requesting an administrator page unless they make a request from the local server. For example, when a request comes from a remote server, the request for/management/DeleteAll will fail.

Code Listing 2-global.asax

 use system, use System.Collections.Generic, use System.Linq, use system.web; SYSTEM.WEB.MVC; Use System.Web.Routing; Use mvcapplication1.constraints; Namespace mvcapplication1{public class MvcApplication:System.Web.HttpApplication {public static void Registerro Utes (RouteCollection routes) {routes.             Ignoreroute ("{resource}. Axd/{* PathInfo}"); Routes. MapRoute ("admin", "admin/{action}", isLocal = new Localhos             Tconstraint ()}); Routes. MapRoute (//"Default",//Route name//"{Controller}/{action}/(number)",//URL with parameter//new {controller = "Home", action = "Cable         ", id ="}//parameter defaults//);         } protected void Application_Start () {registerroutes (routetable.routes); }     } }

Local host constraints are used in the definition of managed routes that this route will not be matched by a remote browser request However, it is important to realize that other routes defined in Global.asax may match the same requests. : A constraint prevents a particular route from matching a request, not all of the routes defined in the file in Global.asax.

Notice that the default route is commented out in the Glabal.asax file in code Listing 2. If you include a default route, the default route will match the request to the management controller. In this scenario, the remote user can still invoke the actions of the management controller, even if their requests do not match the management route.

"Recommended"

1. What is ASP. NET MVC? Summarizing ASP. NET MVC

2. Detailed description of the ASP (mvc--Controller)

3. Detailed description of the ASP. mvc--View

4. Learn more about the difference between ASP. NET MVC and WebForm

5. Code examples for developing custom menu editing tools with ASP.

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.