ASP. NET mvc3 series tutorial-URL-friendly heavy weapons [routing]

Source: Internet
Author: User
Document directory
  • I: Advantages of URL friendliness
  • II: URL-friendly implementation in ASP. NET mvc3
  • III: download an instance with a custom file extension
I: Advantages of URL friendliness

In the past, when developing ASP. NET applications, we often use querystring of the URL to pass parameters to ASP. NET for processing.
For example, http: // localhost: 1029/default. aspx? Key_1 = value_1 & key_2 = value_2 & key_3 = value_3

When using this URL format for portal websites, it is very difficult for search engines to include pages. in addition. the end of aspx will also make search engine crawlers think that this page is a dynamic page and thus give up or drop the page ranking in the search results.

In the face of this problem, the first thing we need to do to please search engine crawlers is:

A: completely disappears querystring, making crawlers think this is an independent page.

B: Change. aspx to a custom suffix format (pseudo static)

C: Configure robots.txt

Example:

Note: The/default/value_1/value_2/value_3.html file does not exist on the hard disk ~

Let's make a comparison
Old URL:

Http: // localhost: 1029/default. aspx? Key_1 = value_1 & key_2 = value_2 & key_3 = value_3

New URL:

Http: // localhost: 2636/default/value_1/value_2/value_3.jsp

Http: // localhost: 2636/default/value_1/value_2/value_3.html

Compared with the previous URL, the new URL is shorter and the custom file suffix format is implemented! It is more conducive to crawling for search and Indexing

In addition
The following paths all belong to one page:
/Default. aspx? Key_1 = something
/Default. aspx? Key_1 = anything

The following paths are divided into multiple pages (from the visitor's perspective ):

/Default/something.html

/Default/anything.html

Such short URLs also help users remember and reflect the site structure. The following is an example:
For example, in my blog, my blog URL is http://www.cnblogs.com/highend/.
Other users' URLs are http://www.cnblogs.com/UserName/.

Because of this user-friendly URL, thus avoiding the appearance of embarrassing URL http://www.cnblogs.com/blog.aspx? Username = highend

Next we will introduce the implementation of user-friendly URLs in ASP. net mvc!

II: URL-friendly implementation in ASP. NET mvc3

After learning about the advantages of URL-friendly, we will introduce you to the URL-friendly routing in ASP. NET mvc3.

TIPS: routes are not unique to ASP. net mvc! It is an important feature in ASP. NET! The routing in MVC only extends the ASP. NET roadside routing function!

1. ASP. NET mvc3 route registration location

After creating an mvc3 project, you can create a global project in the root directory. asax. the CS file defines an inheritance system. web. the mvcapplication class of the httpapplication class, which contains the route settings of mvc3. for details, see the mvcapplication code below.

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 = UrlParameter.Optional } // Parameter defaults    );}protected void Application_Start(){    AreaRegistration.RegisterAllAreas();    RegisterGlobalFilters(GlobalFilters.Filters);    RegisterRoutes(RouteTable.Routes);}

Excerpt msdn introduction to application_start

The application_start and application_end methods are special methods that do not represent the httpapplication event. ASP. NET only calls these methods once during the lifecycle of an application domain, rather than once for each httpapplication instance.

In this mvc3 application, the static method registerroutes (routecollection routes) is called in the application_start () method to enable ASP. NET to instantiate mvchandler, while the routes. maproute (... ) Is the extension method added to routecollection in mvc3, which is located in system. Web. MVC. routecollectionextensions!

Tip: ASP. NET routing is a module located in

C: \ windows \ Microsoft. NET \ framework \ v4.0.30319 \ config \ Web. config

<Httpmodules>
...
<Add name = "UrlRoutingModule-4.0" type = "system. Web. Routing. urlroutingmodule"/>
...
</Httpmodules>

2. Introduction to ASP. NET mcv3 Routing

In the previous section 1st, we already know ASP. net mvc3 for system. web. routing. the routecollection class is extended. I will list the overload list of the extension method below. then, we will detail how to find the one with the most parameters!

System. Web. MVC. routecollectionextensions class-detailed address of the Extension Method list:

The first one I want to introduce is the ignoreroute (string URL) method ~

This function is used to exclude the URL set in the parameter from the routing handler, that is, to ignore the specified URL route for a given list of available routes and constraints.

We reference a line of code in the previous section.

Routes. ignoreroute ("{resource}. axd/{* pathinfo }");

Purpose: Make the routing system ignore web resource files (webresource. axd or scriptresource. axd) that process ASP. NET ).

In addition, the {resource} and {* pathinfo} here cannot be found on the official website for detailed information .~ So I have to ignore it here ~ Follow the maproute function.
 

The maproute method has six overloaded versions in routecollectionextensions! Here I have selected a version with the most parameters for reload introduction.

Public static route maproute (
This routecollection routes,
String name,
String URL,
Object defaults,
Object constraints,
String [] namespaces
)

Name: the unique name of the route in the route list (the name cannot be repeated when maproute is used twice)

URL: URL format of route matching

Defaults: Default Value of Route URL {placeholder}

Constraints: Constraints on {placeholder} of the URL

Namespaces: This is the Controller namespace used to set route search!

The URL, ults, and constraints parameters are described in detail here.

In the code in the previous chapter, maproute uses two special placeholders {controller} and {action} provided in MVC to describe the content as follows:


When maproute is set

routes.MapRoute(    "Default", //name    "{controller}/{action}", //url    new { controller = "Home", action = "Index" }, //defaults    null, //constraints    null //namespaces);

Access

Http: // localhost: 2317/home/Index

{Controller} = home, {action} = index [Note that the submitted URL is case insensitive]

Http: // localhost: 2317/home/about

{Controller} = home, {action} = about

Http: // localhost: 2317/blog/home

{Controller} = blog, {action} = home

Http: // localhost: 2317/account/logon

{Controller} = Account, {action} = Logon

Here we will describe the role of ults .~
When the URL you requested belongs

Http: // localhost: 2317/

{Controller} = NULL, {action} = NULL

Http: // localhost: 2317/home/

{Controller} = home, {action} = NULL

Http: // localhost: 2317/blog/

{Controller} = blog, {action} = NULL

Here ~ Ults will automatically use the default value you set to set {controller} and {action}

New {controller = "home", Action = "Index"}, // defaults

So ~ If the requested URL is in this format of http: // localhost: 2317 // index ~ Defaults does not automatically complete the settings

This is because there must be an order!

OK. The URL parameter will be introduced here first. For more purposes, I will explain it in the next article (Controller & view!

Currently, maproute uses the remaining constraints parameter to add a regular constraint to the previously defined {placeholder}, for example:

Routes. maproute ("constraints", // name "{controller}/{action}", // URL null, // defaults new {controller = @ "[A-Z] {4,}", // The controller must be an English character, the minimum length is 4 Action = @ "[A-Z] {4,}" // action must be an English character; the minimum length is 4 }, // constraints null // namespaces );

For the above maproute, we test the following request URL result:
/Home/Index
/Home/Seo failure
/ABC/defgs failed

If you think that regular expression matching does not meet your requirements, you can implement the system. Web. Routing. irouteconstraint interface to meet your requirements!

Here we mention the string [] namespaces parameter .~

When you create a controller class namespace in your mvc3 application that does not end with controllers, you can set this attribute to allow the routing system to find the namespaces when matching URLs.
Routes. maproute ("namespaces ",
"{Controller}/{action }",
Null, null,
New String [] {"mvcapplication1.custom "}
);

After this parameter is set, the routing system will go
Mvcapplication1.controllers, mvcapplication1.custom with the end of controller inherited from the Controller class!

Describes how to register a route when an area is created:

III: download an instance with a custom file extension


Download source code
In this example, IIS express needs to be changed in the. csproj file if you have not installed IIS Express.
<Useiisexpress> true </useiisexpress> is set to the corresponding value.
Reference: msdn, ASP. net mvc 1.0 Advanced Programming
This article ends now!

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.