ASP. URL rewriting and optimization (beginner)-Customizing URLs using the Global routing table

Source: Internet
Author: User

ASP. URL rewriting and optimization (beginner)-Customizing URLs using the Global routing table

Introduction---

In today's search engine system bully world, we have to do something to please the crawler, and then prompted the site rankings to win a look at the past traffic.

URL rewriting and optimization is one of the means of search engine optimization.

If the URL of a mobile website (based on the ASP. NET MVC) category page is this,

Http://www.xxx.com/category/showcategory?categoryid=1000&view=list&orderby=price&page=1.

Too many querystring are unfriendly to reptiles, and the general practice is to remove unnecessary querystring and make the URL shorter: http://www.xxx.com/category/1000.

But a good URL to semantic, better response to the structure of the site, so the use of the class name as a URL than the classification ID: http://www.xxx.com/categoryname.

Here are some of the two most common requirements for URL rewriting and optimization,

Here will be divided into two articles to solve these two problems.

    • Beginner-Custom URLs using the Global routing table
    • Advanced article-Inherit routebase URL

Here I assume that you crossing already have some knowledge of ASP. Please correct any questions in the text.

First, know the global routing table

When we create an ASP. NET MVC Web program, a Global.asax file is generated. As follows:

View Code

First, Application_Start () is the portal at the time the Web application starts. The <registerglobalfilters () method is used to register the global filter, which is not related to the content of this article >

The RegisterRoutes () method is used to register the routing table

There are two default routing rules already in place:

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

Ignoreroute () is an extension method for the RouteCollection routing table class that ignores the specified routing request. This means ignoring requests that have an. axd file extension. < This method does not detail here >

We mainly look at this one route rule:

Routes. MapRoute (                "Default",//route name                "{controller}/{action}/{id}",//URL with parameter                new {controller = "Home", action = "I Ndex ", id = urlparameter.optional}//parameter default value            );

The MapRoute () method is a method for adding route mappings (an extension method of the RouteCollection class). Here is one of its most common overloads, mapping the specified URL route and setting the default route value:

    • "Default" is the name of the route, which is unique in the collection of routes for the application (the Routes object) and will be an error if the duplicate name is generated.
    • ' {Controller}/{action}/{id} ' represents a URL expression for a route.
    • New {controller = "Home", action = "Index", and id = urlparameter.optional} declares an object that contains The route value for anonymous objects .

This statement adds a routing rule that maps the URL expression to a route value-pointing to an action method under a controller.

e.g.: We enter a relative address in the browser/home/index the Homecontroller.index () method is called.

When publishing a Web site, the Global.asax file is compiled into a DLL. When the program starts, it calls the Application_Start () method First,

After the RegisterRoutes (routetable.routes) statement is executed, the routing table is registered and the default routing rule takes effect.

With this default rule, we can use/controllername/actionname?querystring= ... Such a relative URL to invoke each action method in the program.

People familiar with ASP. NET MVC can think of, if there is no special requirements of the system, such as the site backstage, there is no need to toss, a default route rule is sufficient to prop up the entire Web program.

Two, route matching rules

1. First of all, we need science. How to define a URL expression.

First, the URL expression is relative , not including the host domain name part (such as http://www.xxx.com). {} the placeholder is saved,"/", "." It is used as a delimiter, and nothing is static content:

    • url/category/showcategory/1000 matches "{Controller}/{action}/{id}".
    • Url/product/2012/4/28.html matches the "/product/{year}/{month}/{day}.html", and so forth.

It is important to note that {Controller} and {action} are two reserved placeholders, each representing the corresponding controller name and operation name.

The name of the controller (s), which is defined as the controller suffix, is removed, Categorycontroller is category

{action} corresponds to the name of the action method within the controller.

  2. There are two different kinds of operations for routing.

  gets the route value , when you enter a URL in the browser, the program will match the URL expression in the route table we added to find the corresponding route value.

Let's take a look at an example and we'll add two routing rules.

Routes. MapRoute ("Test", "where-are-you-going", new {controller = "Home", action = "Index"}), routes. MapRoute ("Test1", "where-are-you-going", new {controller = "Home", action = "Others"});

Suppose there are two actions in HomeController that are index () and others () respectively.

You crossing think in the browser input http://www.xxx.com/where-are-you-going which method will be called? What if it's upside down?

< call Homecontroller.index ()/Call homecontroller.others> after reverse

  To get the URL, the following code uses the Url.action method to fully qualify a URL using the controller and the action name.

That is, we have a route value, by matching in the routing table, we can find the corresponding URL pattern, and then generate a URL

<a href= "@Url. Action (" Index "," Home ") > Home </a>

Now let's add one of the following routing rules under the default routing rules

Routes. MapRoute ("MyHome", "Myhome/{id}", new {controller = "Home", action = "Index", id = urlparameter.optional});

What do you think the page will show?

<a href= "http://www.xxx.com/" > Home </a>or<a href= "Http://www.xxx.com/myhome" > Home </a>

 

What if this routing rule is written on top of the default rule?

< who writes on the top shows its matching url>

  3. The above questions you can try it yourself, it is clear that the route matching is top-down , as long as the match to the first record, will return the corresponding URL or route value.

This is very important. Many people always find that their rules do not take effect when they customize routing rules. Then you should check if it was overwritten by the previous route.

Third, solve the problem of the beginning

From the URL of this station can be seen,

Http://www.xxx.com/category/showcategory?categoryid=1000&view=list&orderby=price&page=1,

Should be used only as a default routing rule,

You can infer that there is a controller named category, which has a method named Showcategory, the required parameter is CategoryID, and the other is an optional parameter.

The knowledge of URL rewriting is done based on the global routing table described above.

According to the webmaster's requirements, we just need to add a routing rule is done. Isn't it simple?

Routes. MapRoute ("category", "Category/{categoryid}", new {controller = "category", action = "Showcategory"}

  

This time must pay attention to Oh, do not write in the default route below, you understand. Or you're going to be a tragedy.

In general, we recommend that if you need to use the Globel file to customize the route, delete the original default route and customize your own route for each action.

Routes. MapRoute ("Home", "" ", new {controller =" Home ", action =" Index "});

Use the route above to replace the default route.

The Homecontroller.index () method is called when the browser enters a relative URL "/".

The reason for this is that the default route is prone to conflict with custom routing.

We strongly recommend that you play the global file yourself and rewrite the URL to get a feel for yourself. There's actually a suspense I left for everyone,

Why is the URL to get the first page under the default rule "/" instead of "/home/index"? ^_^

Matching rules also have greedy matches and default matches one says, this leaves everyone to understand.

There are many limitations to using global, in the example above because the method Showcategory has a parameter CategoryID, which exists with the routing information in the key-value pair,

At configuration time, we can use the placeholder {CategoryID} to display it.

For URLs such as Http://www.xxx.com/categoryname, if you do not modify the program, Global is powerless because CategoryName does not exist in the key-value pairs of the routing information.

The need for such a more complex and variable URL rewriting and optimization is always complex and variable. =).

---------------------------------------the end of the junior chapter--------------------------------------------

ASP. URL rewriting and optimization (beginner)-Customizing URLs using the Global routing table

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.