Learn about ASP. NET MVC: URL Routing

Source: Internet
Author: User

Learn about ASP. NET MVC: URL Routing
Summary:

Before the MVC framework, ASP. NET assumes that there is a direct relationship between the requested URLs and the server hard disk files. The role of the server is to receive browser requests to send output from the appropriate file.

This method works only on Web forms, and each ASPX page is both a file and a self-contained response to a corresponding request. This is not valid for MVC applications because the request is handled by the behavior method in the Controller class, and there is no one-to-one relationship on the disk.

Asp. NET platform uses a routing system to process MVC URLs. In this article, I'll show you how to use the routing system for your project to create and work with powerful, flexible URLs. You will see that the routing system allows you to create any form of URLs you need and express them in a clear and concise manner. There are two functions of the routing system:

Check the incoming URL to figure out which controller and behavior method it intends to be.

Generate external URLs. These URLs are displayed in the HTML of the view, so that when the user clicks on the hyperlink, a specific behavior method is triggered (at this point, it becomes the incoming URL).

In this chapter, I'll describe the definition of routes and the URLs they use to process requests so that users can invoke your controller and behavior methods. In the MVC framework, there are two ways to create a route. Based on traditional routing and feature routing. If you've used earlier versions of the MVC framework, you might be familiar with traditional routes. Feature routing is a new addition to MVC5. This article will describe them separately.

In the next article I'll show you how to use those same routes to generate external URLs that you need to include in your view. And how to use a function called areas to implement a custom routing system.

Prepare the case Project

HomeController:

Copy Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using SYSTEM.WEB.MVC;
6
7 namespace Urlsandroutes.controllers
: 9
9 public class Homecontroller:controller
10 {
Public ActionResult Index ()
12 {
Viewbag.controller = "Home";
Viewbag.action = "Index";
Return View ("ActionName");
16}
17}
18}
Copy Code
Customercontroller:

Copy Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 Using SYSTEM.WEB.MVC;
6
7 namespace Urlsandroutes.controllers
8 {
9 public class Customercontroller:controller
Ten {
11 Public ActionResult Index ()
{
Viewbag.controller = "Customer";
Viewbag.action = "Index";
Return View ("ActionName");
16}

Public ActionResult List ()
{
Viewbag.controller = "Customer";
Viewbag.action = "List";
Return View ("ActionName");
23}
24}
25}
Copy Code
Admincontroller:

Copy Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using SYSTEM.WEB.MVC;
6
7 namespace Urlsandroutes.controllers
8 {
9 public class Admincontroller:controller
10 {
Public ActionResult Index ()
12 {
Viewbag.controller = "Admin";
Viewbag.action = "Index";
Return View ("ActionName");
16}
17}
18}
Copy Code
Within the Views subfolder shared, create the view file actionname.cshtml.

Copy Code
1 @{
2 Layout = null;
9 ·
4 <! DOCTYPE html>
5 6 7 <meta name= "viewport" content= "Width=device-width"/>
8 <title>ActionName</title>
9 Ten <body>
<div>the controller is: @ViewBag .controller</div>
<div>the action is: @ViewBag .action</div>
</body>
Copy Code
In the project properties, select Web Options. Select specific Page.

Run the program and get the result:

Introducing the URL pattern

The routing system uses a collection of routes to show his magic. These routes collectively form the URL pattern, or a system pattern (a collection of URLs that your application can recognize and respond to).

I don't need to manually write all the URLs that will be supported in my application. Instead, each route contains a URL pattern, which is compared to the URLs entered. If the URL conforms to this pattern, it will be routed to the system to process the URL. Let's start with a URL for the sample application:

Http://mysite.com/Admin/Index

URLs can be divided into sections. They are part of the URL, and they are separated by a/character except for the hostname and query-argument-string. In this example, there are two sections:

Http://mysite.com/Admin/Index

First Second

The first section contains the word admin, and the second section contains the word index. In the human eye, the first section detail is associated with the controller, and the second section relates to the behavior method. But, of course, I need a way to express this kind of relationship that the routing system can understand. The following is a URL pattern:

{Controller}/{action}

When processing a incoming request, the routing system works by matching the requested URL to a pattern and extracting the variables from the URL that are defined in the schema species. The variables for these sections are expressed using the parentheses {} character. This example has two section variables, the names of which are controller and action. So the value of the Controller section variable is the value of the Admin,action section variable is index.

I say match a pattern, because the MVC system often has many routes, the routing system will compare the URLs entered and each route in the URL pattern until a match is found.

By default, a URL pattern will match any URL of the same quantity section. For example, the schema {controller}/{action} will match any URL that has two sections.

Requested URL section variable
Http://mysite.com/Admin/Indexcontroller www.120xh.cn = Admin action = Index
Http://mysite.com/Index/Admincontroller www.yigouyule2.cn = Index action = Admin
Http://mysite.com/Apples/Orangescontroller = Apples Www.meiwanyule.cn/action = oranges
Http://mysite.com/AdminNo Match-too Few segments
Http://mysite.com/Admin/Index/SoccerNo Match-too Many segments

Two key behaviors of the URL pattern:

The URL pattern is conservative, and it only matches the pattern URL for the same number of sections. The fourth and fifth examples in the table.
The URL pattern is open. If a URL does contain the same number of sections, the pattern extracts the value of the section variable, regardless of what it might be.

The default behavior of these things is also the key to understanding how the URL pattern works. The following describes how to change this default behavior.

As already mentioned, the routing system does not know any information about the MVC system. The URL pattern will still match when the variable extracted from the URL does not have a corresponding controller or action. A second example in the table is. I transpose the admin and Index sections in the URL, and the values extracted from the URL are then transpose, even though the example project does not have the index controller.

Create and register a simple route

Once you understand the URL pattern, you can use it to define the route. The route definition is in the RoutConfig.cs code file in the App_start project folder. You will see the initial contents of this file as defined by Visual Studio:

Copy Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 Using SYSTEM.WEB.MVC;
6 using System.Web.Routing;
7
8 namespace Urlsandroutes
9 {
public class Routeconfig
One {
) public static void Registerrout ES (routecollection routes)
{
routes. Ignoreroute ("{resource}.axd/{*pathinfo}");

Routes. MapRoute (
. Name: "Default",
URL: "{controller}www.chaoyueyule.com/{action}www.huachengj1980.com//{id}",
Defaults:new {controller = "Home", action = "Index", id = urlparameter.optional}
20);
21}
22}
23} The
Copy code
defines the static Registerrouters method in the RoutConfig.cs file, which is called in the Global.asax.cs file. The Global.asax.cs file sets some MVC core functionality when the application starts. You will see the default contents of the Global.asax.cs file. I made a bold call to the Routeconfig.registerroutes method within the Application_Start method.

Copy Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using SYSTEM.WEB.MVC;
6 using System.Web.Routing;
7
8 namespace Urlsandroutes
9 {
public class MvcApplication:System.Web.HttpApplication
11 {
protected void Application_Start ()
13 {
Arearegistration.registerallareas ();
Routeconfig.registerroutes (routetable.routes);
16}
17}
18}
Copy Code
The Application_Start method is called by the background ASP. NET platform when the MVC application is first launched. Causes the Routeconfig.registerroutes method to be called. The parameter of the Routetable.routes method is the value of the static property, which is an instance of the RouteCollection type.

The following code creates its own URL pattern.

Copy Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using SYSTEM.WEB.MVC;
6 using System.Web.Routing;
7
8 namespace Urlsandroutes
9 {
public class Routeconfig
11 {
public static void RegisterRoutes (RouteCollection routes)
13 {
Routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
15
Route Myroute = new Route ("{controller}/{action}", New Mvcroutehandler ());
Routes. ADD ("Myroute", Myroute); 18}
19}
20}
Copy Code
I use the constructor string parameter and a Mvcroutehandler instance parameter to create a new route. Different ASP. NET technologies provide different classes to handle the routing behavior. Mvcroutehandler is an ASP. NET MVC application that is used by default. After creating the route, I use the Add method to add him to the RouteCollection object.

A more convenient way to register a route is to use the Maproute method defined in RouteCollection. The following code works the same as above.

Copy Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using SYSTEM.WEB.MVC;
6 using System.Web.Routing;
7
8 namespace Urlsandroutes
9 {
public class Routeconfig
11 {
public static void RegisterRoutes (RouteCollection routes)
13 {
Routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
15
Routes. MapRoute ("Myroute", "{controller}/{action}");
17}
18}
19}
Copy Code
This method is more compact, mainly because I do not need to create an instance of the Mvcroutehandler class (it is created by default in the background). The Maproute method applies only to MVC applications. The ASP. NET Web Form program uses the Mappageroute method defined in the RouteCollection class.

Use this simple route

Starting the sample application, you can see the effect I've modified after routing. If you navigate to the root path of the application, you will see a page that shows the error. But if you navigate to a route that conforms to the {controller}/{action} pattern, you will see the following result, which shows the effect of navigating to/admin/index.

Define default values

When I request the default URL for the application to get an error page, it is because it does not match the route I defined. The default URL expression is ~/in the routing system, and there is no section in the string that matches the controller and Behavior methods.

I've explained that the URL patterns are conservative, and they will match the URLs of the equal numbers section. I also said this is the default behavior, the way to change this behavior is to use the default value. When a URL does not contain a section that matches a value, the default value is used. The following code provides an example of a default value:

Copy Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using SYSTEM.WEB.MVC;
6 using System.Web.Routing;
7
8 namespace Urlsandroutes
9 {
public class Routeconfig
11 {
public static void RegisterRoutes (RouteCollection routes)
13 {
Routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
15
Routes. MapRoute ("Myroute", "{controller}/{action}", new {action = "Index"});
17}
18}
19}
Copy Code
The default value is provided as a property of the anonymous class. In the above example, I gave the action variable a default value of index. This route will match all of the previous two-section URLs. For example, when Url:http://mydomain.com/home/index is requested, the route extracts Home as the controller variable value, index as the action variable value.

Now that I have provided default values to the Action section, the routing system will also match the URLs of the individual sections. When working with a single section URL, the routing system extracts the controller value from a single URL section, with the default value being the value of the action variable. In this way, I can request url:http://mydomain.com/home to trigger the index behavior method in the Home controller.

I can also go farther, define a URLs that do not contain any section variables, and rely only on the default values to identify the action and controller. The following code shows how to provide a default value of two sections to map to the root URL of the application.

Copy Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using SYSTEM.WEB.MVC;
6 using System.Web.Routing;
7
8 namespace Urlsandroutes
9 {
public class Routeconfig
11 {
public static void RegisterRoutes (RouteCollection routes)
13 {
Routes. Ignoreroute ("{resource}.axd/{*pathinfo}");
15
Routes. MapRoute ("Myroute", "{controller}/{action}", new {controller = "Home", action = "Index"});
17}
18}
19}
Copy Code
By providing default to the Controller and action variables, the route I created will match the following URLs.

Number of Segmentsexamplemaps to
0mydomain.comcontroller = Home action = Index
1mydomain.com/customer Controller = Customer action = Index
2mydomain.com/customer/listcontroller = Customer action = List
3mydomain.com/customer/list/allno Match-too Many segments

The fewer nodes that are received in the incoming URL, the more default values will be relied upon. Until I receive a URL without a section, all default values are used. Start the application, navigate to the root URL, and see the results of the run:

Learn about ASP. NET MVC: URL Routing

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.