ASP. NET MVC programming--routing

Source: Internet
Author: User

Framework auto-generated routing configuration

, the routing configuration file is RouteConfig.cs under the App_start folder.

The code is as follows:

 Public classrouteconfig{ Public Static voidregisterroutes (routecollection routes) {routes. Ignoreroute ("{Resource}.axd/{*pathinfo}"); Routes. MapRoute (Name:"Default", URL:"{Controller}/{action}/{id}", defaults:New{controller ="Home", action ="Index", id =urlparameter.optional}); }}

Note: The controllers and operations in the route are not case-sensitive.

Ignore route

Ignoreroute is a routecollection extension method that ignores routes of the specified style.

Above routes. Ignoreroute ("{resource}.axd/{*pathinfo}"), {resource} in represents a route parameter, {Resource}.axd represents a string ending with. axd; {*pathinfo} is also a route parameter , * represents matching any string, then the string ending with PathInfo will match. The complete meaning of this statement is: any string ending in Axd, regardless of the string after the slash, does not perform the routing behavior.

Map routes

Maproute is also an extension method for routecollection, which maps routes.

Maproute has multiple overloaded methods, all parameters have the following meanings:

Parameter name

Parameter type

Comments

Name

String

Route Name

Url

String

URL pattern

Defaults

Object

Default route Value Object

Constraints

Object

A set of expressions that qualify URL parameter values

Namespaces

String[]

Set up a set of namespaces

Parameter resolution

1) Defaults set the default route value object,

2) Constraints: Set constraints by regular expressions

such as constraints:new {[email protected] "\d+"} limit ID can only be numeric type

rules: Front to back segment matching, request When the URL parameter is less than the defined URL, the default configuration complements the corresponding parameters.

A few examples:

Routes. MapRoute (

Name: "",

URL: "V1/{controller}/{action}/{id}",

defaults:new {controller = "Home", action = "Index", id = urlparameter.optional},

constraints:new {[email protected] "\d+"}

);

3) URL

{Controller}/{action}/{id}

This form consists of three paragraphs, which refer to the portion of the route used/separated. The controllers and actions in the contract route are expressed with the Controller and action.

Segments can also contain literal values.

There are two consecutive segment values that are not allowed:

For example

Not allowed: {Controller}{action}/{id}

Legal: {Language}-{current}/{controller}/{action}/{id}

Selection issues for multiple routes

When multiple routes are configured, they are matched from top to bottom until they are matched to one.

Match an existing file

Determine whether an existing file can be matched by setting the Routecollection.routeexistingfiles property. If, routes. Routeexistingfiles = false; it is forbidden to match to an existing file, only to match the virtual route in the routing table.

Cases:

public static void RegisterRoutes (RouteCollection routes)

{

Routes. Routeexistingfiles = true;

Other configurations

}

Configuring Routes with Attributes

Marks the property Routeattribute on the controller or controller action.

[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, inherited = False, AllowMultiple = True)]

Public sealed class Routeattribute:attribute, Idirectroutefactory, Irouteinfoprovider

Use three attributes or constructors for an attribute:

Public Routeattribute (string template): Template is a route matching pattern

Name: Gets or sets the route name

Order: Gets or sets the route application sequence

Template: Get route matching mode

URL and search engine optimization

1) The shorter the URL, the better.

2) Use dashes instead of underscores

3) use lowercase letters. According to the HTTP specification, URLs are case-sensitive, and generic search engines follow the HTTP specification.

Use Glimpse observing Routes

installation Glimpse

address http://getglimpse.com/Docs/#download找到所需安装命令. You can see on the website that not only applies to MVC, it is mainly used to observe the route, so download the MVC package.

Open Vs-> Tools->nuget Package Manager, Package Manager console, enter commands on the console: Install-package glimpse.mvc5, and then enter to perform the installation with the following results:

enabled Glimpse

To run the Web app, enter the address format: Web site root directory/glimpse.axd, for example

Http://localhost:51881/glimpse.axd, the display interface is as follows, click Turn Glimpse on to start.

Use Glimpse Observation

started the After glimpse, enter http://localhost:51881/Home/Contact and see

Note that there is more than one statistic below the browser, where you can see information about the routing request, as an example of the address entered above:

Browser Request time consuming

Service-side response time-consuming

Click on the icon below to see more detailed information.

The interface for displaying detailed information is as follows:

From there, you can see configuration, runtime Environment, model bindings, requests, routes, servers, time statistics, and so on.

Extended Route - Create a custom route constraint

Inherit the Irouteconstraint interface to implement the match method

 Public class customrouteconstraint:irouteconstraint{        publicbool string  ParameterName, routevaluedictionary values, routedirection routedirection)        {            // Implementation Validation             // verify by returning True            return true ;        }}

Working with constraints

routes. MapRoute (Name:"Customconstr", URL:"{Controller}/{action}/{id}", defaults:New{controller ="Home", action ="Index", id =urlparameter.optional}, Constraints:New{id=Newcustomrouteconstraint ()});

Principle

1) First, urlroutemodule processes the new request and maps the request URL to the defined router.

2) If the URL matches the defined route, create the Iroutehandler instance (the default instance is the Mvcroutehandler object).

3) Iroutehandler Returns an instance of the HTTP processor (the default is Mvchandler), and the HTTP processor instance is responsible for processing the request message.

4) The HTTP processor instance uses Icontrollerfactory (Controller factory) to create the corresponding controller object.

Attention:

for 1) if the requested URL matches the entity file in the root directory of the Web site, the virtual route is no longer matched unless the behavior is set by Routecollection.routeexistingfiles.

Reference:

1.Jess chadwick/todd Snyder/hrusikesh Panda, Xu Lei/Xu Yang

Translated. ASP. NET MVC4 Web programming

2.Jon Galloway/phil Haack/brad wilson/k Scott Allen, Sun/Shang translate ASP. NET MVC4 Advanced Programming (Fourth Edition)

3. Huangpao, ASP. MVC4 Development Guide

4. Jing Jinnan, ASP. NET MVC4 Framework

5.https://www.asp.net/mvc

-----------------------------------------------------------------------------------------

Reprint and quote please specify the source.

Time haste, the level is limited, if has the improper place, welcome correction.

ASP. NET MVC programming--routing

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.