Asp.net MVC Learning (1)-Routing

Source: Internet
Author: User
1. Understand the default route table

When you create a new ASP. net mvc application, the application has been configured to use ASP. NET routing. ASP. NET routes are set in two places.

First, enable ASP. NET routing in your application Web configuration file (Web. config file. The configuration file contains four nodes and routes: sytem. web. httpModules, system. web. httpHandlers, system. webserver. modules, and system. webserver. handlers. Be careful not to delete these nodes because they cannot work without routes.

Second, it is more important to create a route table in the Global. asax file of the application. The Global. asax file is a special file that contains Event Handlers acting on ASP. NET application lifecycle events. The route table is created during the Application Start event.

The file in code list 1 contains the default Global. asax file for an ASP. net mvc application.

Code List 1-Global. asax. cs

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Mvc;
Using System. Web. Routing;

Namespace MvcApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// Visit http://go.microsoft.com /? LinkId = 9394801

Public class MvcApplication: System. Web. HttpApplication
{
Public static void RegisterRoutes (RouteCollection routes)
{
Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");

Routes. MapRoute (
"Default", // Route name
"{Controller}/{action}/{id}", // URL with parameters
New {controller = "Home", action = "Index", id = ""} // Parameter defaults
);

}

Protected void Application_Start ()
{
RegisterRoutes (RouteTable. Routes );
}
}
}

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

The Default route table contains a route (named Default ). The Default route maps the first part of the URL to the Controller name, the second part of the URL to the Controller action, and the third part to a parameter named id.

Suppose you entered the following URL in the address bar of your 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, the following code is executed:

HomeController. Index (3)

The Default route contains the Default values of all three parameters. If you do not provide a controller, the default controller parameter is Home. If you do not provide an action, the default value of the action parameter is Index. Finally, if you do not provide an id, the id parameter is a null string by default.

Let's take a look at several examples of how the Default route maps URLs to Controller actions. Suppose you entered the following URL in the address bar of your browser:

/Home

Because of the Default value of the Default route parameter, entering this URL will call the Index () method of the HomeController class in code list 2.

Code List 2-HomeController. cs

Using System. Web. Mvc;

Namespace MvcApplication1.Controllers
{
[HandleError]
Public class HomeController: Controller
{
Public ActionResult Index (string id)
{
Return View ();
}
}
}

In code list 2, The HomeController class contains a method called Index (), which accepts a parameter called Id. URL/Home will call the Index () method and use an empty string as the value of the Id parameter.

Out of the way the MVC Framework calls the Controller action, URL/Home also matches the Index () method of the HomeController class in listing 3.

Code List 3-HomeController. cs (Index action without parameters)

Using System. Web. Mvc;

Namespace MvcApplication1.Controllers
{
[HandleError]
Public class HomeController: Controller
{
Public ActionResult Index ()
{
Return View ();
}
}
}

The Index () method in listing 3 does not accept any parameters. URL/Home will call this Index () method. URL/Home/Index/3 will also call this method (Id is ignored ).

URL/Home also matches the Index () method of the HomeController class in Listing 4.

Code list 4-HomeController. cs (using the Index action with null parameters)

Using 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 void parameter (which can have a Null value), you can call Index () without causing an error.

Finally, using URL/Home to call the Index () method in listing 5 will cause an exception because the Id parameter is not an empty parameter. If you try to call the Index () method, you will get an error shown in Figure 1.

Code List 5-HomeController. cs (Index action with Id parameter)

Using System. Web. Mvc;

Namespace MvcApplication1.Controllers
{
[HandleError]
Public class HomeController: Controller
{
Public ActionResult Index (int id)
{
Return View ();
}
}
}

Figure 01: Call a controller action with the expected parameter value

On the other hand, URL/Home/Index/3 works well with the Index controller action in code listing 5. The/Home/Index/3 request will call the Index () method containing an Id, and the Id value is 3.

This tutorial aims to provide you with a brief introduction to ASP. NET routing. We carefully checked the default route table, which is obtained when you create a new ASP. net mvc application. You learned how to map URLs to Controller actions in the default route table.

2. Create a custom route

In this tutorial, you will learn how to add custom routes to ASP. net mvc applications. You will learn how to change the default route table in the Global. asax file to a custom route.

For simple ASP. net mvc applications, the default route table can be well completed. However, you may find that there are specific routing requirements. In this case, you can create a custom route.

Imagine, for example, you are creating a blog application. You may want to process the coming request like this:

/Archive/12-25-2009

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

In code list 1, Global. asax contains a new custom Route named Blog, which processes requests such as/Archive/entry date.

Code List 1-Global. asax (including custom routes)

Using System. Web. Mvc;
Using System. Web. Routing;

Namespace MvcApplication1
{

Public class MvcApplication: System. Web. HttpApplication
{
Public static void RegisterRoutes (RouteCollection routes)
{
Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");

Routes. MapRoute (
"Blog", // Route name
"Archive/{entryDate}", // URL with parameters
New {controller = "Archive", action = "Entry"} // Parameter defaults
);

Routes. MapRoute (
"Default", // Route name
"{Controller}/{action}/{id}", // URL with parameters
New {controller = "Home", action = "Index", id = ""} // Parameter defaults
);

}

Protected void Application_Start ()
{
RegisterRoutes (RouteTable. Routes );
}
}
}

The route order added to the route table is very important. Our new custom Blog route is placed before the existing Default route. If you turn this order upside down, the Default route will always be called, rather than a custom route.

Custom Blog routes match any requests starting with/Archive. Therefore, it matches all the following urls:

/Archive/12-25-2009

/Archive/10-6-2004

/Archive/apple

Custom routing maps incoming requests to the Controller named Archive and calls the Entry () action. When the Entry () method is called, the Entry date is passed as the entryDate parameter.

Code List 2-ArchiveController. cs

Using System;
Using System. Web. Mvc;

Namespace MvcApplication1.Controllers
{
Public class ArchiveController: Controller
{

Public string Entry (DateTime entryDate)
{
Return "You requested the entry from" + entryDate. ToString ();
}

}
}

Note that the Entry () method in Listing 2 accepts a DateTime-type parameter. The MVC framework is very clever enough to automatically convert the entry date in the URL to the DateTime value. If the date parameter of the entry in the URL cannot be converted to DateTime, an error (1) is thrown ).

Figure 1-Incorrect conversion Parameters

The purpose of this tutorial is to demonstrate how to create a custom route. You learned how to add a custom route in the routing table of the Global. asax file. This route represents a blog entry. We discussed how to map requests to blog entries to the Controller named ArchiveController and the Controller action named Entry.

3. Create route Constraints

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

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

Code List 1-Global. asax. cs

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

Code List 1 contains a route called Product. You can use the Product route to map browser requests to ProductController in code list 2.

Code List 2-ControllersProductController. cs

Using System. Web. Mvc;

Namespace MvcApplication1.Controllers
{
Public class ProductController: Controller
{
Public ActionResult Details (int productId)
{
Return View ();
}
}
}

Note that the Details () Action published by the Product controller accepts a parameter called productId. This parameter is an integer parameter.

The routes defined in code list 1 match any of the following urls:

  • /Product/23
  • /Product/7

Unfortunately, the route will also match the following URL:

  • /Product/blah
  • /Product/apple

Because the Details () Action expects an integer, initiating a request containing a non-integer value will cause an error. For example, if you enter/Product/apple URL in your browser, you will get the error page shown in Figure 1.

Figure 1: Error Page

What you actually want to do is to match only the URL containing the appropriate integer productId. When you define a route to restrict URLs that match the route, you can use the constraint. The modified Product route in code 3 contains a regular expression that limits matching only numbers.

Code List 3-Global. asax. cs

Routes. MapRoute (
"Product ",
"Product/{productId }",
New {controller = "Product", action = "Details "},
New {productId = @ "d + "}
);

The regular expression d + matches one or more integers. This restriction matches the Product route with the following URL:

  • /Product/3
  • /Product/8999

But does not match the following URL:

  • /Product/apple
  • /Product

These browser requests will be processed by another route, or, if there is no matching route, a "The resource cocould not be found" error will be returned.

4. Create a custom route Constraint

The purpose of this tutorial is to demonstrate how to create a custom route constraint. Custom route constraints allow you to prevent a path from being matched unless you meet custom conditions.

In this tutorial, we created a Localhost routing constraint. The Localhost routing constraint only matches the requests sent by the local computer. Remote requests sent over the Internet are not 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 values,
RouteDirection routeDirection
)

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

The Localhost constraint is included in code listing 1.

Code List 1-LocalhostConstraint. cs

Using System. Web;
Using 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 code list 1 use the IsLocal attribute published by the HttpRequest class. If the IP address of the request is 127.0.0.1 or the IP address of the server is the same, true is returned.

You use custom constraints in the routing defined in Global. asax. The Global. asax file in code list 2 uses the Localhost constraint to prevent anyone from requesting the Admin page, unless they send requests from the local server. For example, when a request comes from a remote server, the/Admin/DeleteAll request fails.

Code List 2-Global. asax

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Mvc;
Using System. Web. Routing;
Using MvcApplication1.Constraints;

Namespace MvcApplication1
{

Public class MvcApplication: System. Web. HttpApplication
{
Public static void RegisterRoutes (RouteCollection routes ){
Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");

Routes. MapRoute (
"Admin ",
"Admin/{action }",
New {controller = "Admin "},
New {isLocal = new LocalhostConstraint ()}
);

// Routes. MapRoute (
// "Default", // Route name
// "{Controller}/{action}/{id}", // URL with parameters
// New {controller = "Home", action = "Index", id = ""} // Parameter defaults
//);
}

Protected void Application_Start (){
RegisterRoutes (RouteTable. Routes );
}
}
}

The Localhost constraint is defined in the Admin route. This route will not be matched by remote browser requests. However, you should be aware that other routes defined in Global. asax may match the same request. Understanding this is important: constraints prevent a specific route from matching a request, rather than all the routes defined in the Global. asax file.

Note that the Default route is commented out in the Glabal. asax file in code list 2. If you include the Default route, the Default route matches the request to the Admin controller. In this case, remote users can still call the actions of the Admin controller even if their requests do not match the Admin route.

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.