A simple instance step-by-step help you figure out the routes and areas in the MVC3

Source: Internet
Author: User
Tags naming convention

We all know that all the requests for the MVC 3 program are routed through route parsing and then assigned to a specific controller and Action, why is this knowledge finished after the controller Action Model is spoken? This thing I personally feel compared to the abstract bar! If you have a foundation, it looks effortless, and if you don't have a foundation, you don't even know what the controller Action is, how do you understand routing? Hey, it's just a personal view! If you have not yet understood some basic information about MVC 3, please follow my navigation below to learn more about MVC 3 and then look at this article. In the previous article, all the things that involve routing knowledge have a simple explanation of the route, and for those who don't yet know the routing concept, there is no obstacle to reading the following articles.

1. ASP. NET MVC 3
2. ASP. NET MVC 3 environment installation and configuration
3. ASP. NET MVC 3 Razor view engine basic syntax
4. ASP. NET MVC 3 Razor view engine layout
5. ASP. NET MVC 3 Controller
6. ASP. NET MVC 3 Model "Step-by-step introduction to a simple example"

Okay, let's talk about it. Routing Routing
First, if Routing's namespace is System.Web.Routing, in this case, Routing is not exclusive to MVC 3, but it is also used in WebForm. Of course I have not used, but everyone has done the project has used the URL rewrite it! If you have not used the URL rewriting technology, prove that you do not need to do the project SEO.

The role of the second routing:
1. Determine controller 2. Determine action 3. Determine the other parameters (typically the parameters of the action method) 4. The request is passed to the controller and Action for the response, based on the identified controller action.

How the third Routing works:
We think of a problem for the following URL http://www.cnblogs/wlitsoft/blogs/123 Why do I implement a controller when I visit this URL wlitsoft Action is blogs The parameter is 123?
Well, we all know that the MVC 3 project has a global file (global.asax) with the directory, and of course the file is used in the WebForm, so let's see how it differs from WebForm or how it's added.

1 Routes.maproute (
2 "Default",//route name
3 "{Controller}/{action}/{id}",//URL with parameters
4 new {controller = "Home", action = "Index", id = urlparameter.optional}//parameter default value
5);

We will find the above lines of code. These lines of code define a route matching rule, and let's take a look at what the specific parameters mean.
-Name parameter: rule name, can not be duplicated, that is, the route name must be unique.

-url parameter: Enclose the parameter that will be recognized, for example: {Controller}/{action}/{id} here {} is a placeholder you can understand that everyone has used the format method of the String Class!
For example: String. Format ("{0}AAAA{1}BBB", "1", "2");

-Defaults parameter: The default value of the URL parameter, when we create a new MVC project when running Browse can see the address bar without any parameters only one such as http://localhost:32112/it turned to the index page under home? This is what this parameter does, it can define the default controller action and the ID parameter. You see the code above, why does the ID not give a specific value, but to a urlparameter.optional? Because you cannot guarantee that the type of ID is int or stirng, and so on, write id= urlparameter.optional It will specify what type of default value, such as int, is 0 depending on the type of ID.

-Constraints parameter: This parameter does not appear in the code above again I'll say it in advance and then we'll look at the code in a minute!
The function of this parameter is to qualify the rule for each parameter or the type of the HTTP request Constraints property is a RouteValueDictionary object, which is a dictionary table, but the value of this dictionary table can have two kinds: 1. A string used to define a regular expression. The regular expression is case-insensitive 2. An object that implements the Irouteconstraint interface and contains the match method.
For example, a regular expression allows you to specify a parameter format, such as a controller parameter that can only be 4 digits.

New {controller = @ "\d{4}"}

The type of request can currently be restricted through the Irouteconstraint interface.
For example, restricting a routing rule can only handle GET requests:

HttpMethod = new Httpmethodconstraint ("GET", "POST")

Iv. How to optimize URLs
For a site for SEO-friendly, a URL layer should not exceed 3 layers: But according to our default matching rule {Controller}/{action}/{id} It is 3 layers and does not conform to the SEO how to do? Just a little change to see how to modify {Controller}/{action}-{id} We all know that C # 's naming convention is that alphanumeric underscores cannot start with a letter, so the URL mapped by {Action}-{id} will not be matched to a variable.

Fifth route matching is a priority
Route matching is a priority, which means that you define the routing rules in order, if you define a very complex route but you put it at the bottom, it happens that the above routing rules are compliant then you hang up and never match the route you defined. How to do pinch the not easy to match the route on the top, the most easy to match the route at the bottom, here I have to say that there is a route to match all the URLs what? Look at the following code
{*allurl}

Section six regional area such as a management system has a background function it! But we want to make the backstage management this block and the website front desk separate or this says backstage management This fast saves a separate Web. config profile what to do? Here's the concept of the area. We'll start with a new area.

When you're finished, you'll see a AreaAdminAreaRegistration.cs file open it
Copy Code

1 public override void Registerarea (AreaRegistrationContext context)
2 {
3 context. MapRoute (
4 "Areaadmin_default",
5 "Areaadmin/{controller}/{action}/{id}",
6 new {action = "Index", id = urlparameter.optional}
7);
8}

Copy Code

Rewrite a method how to identify in the global file? Look at the global file

1 protected void Application_Start ()
2 {
3 Arearegistration.registerallareas ();
4
5 registerroutes (routetable.routes);
6}

Line 3rd is not defined so the zone this routing rule in addition to the previous add a Areaadmin area name and the other there is no difference! Let's start with a new controller like Adminhome. Let's avoid the same name as the old controller for a while. Look at the results of the operation

It's normal! But if I'm going to create a new homecontroller, I'll build a controller that I used to have at the front desk and run it.

It's no problem, is it? Okay, let's go back to the other HomeController, which is the front desk, and see what's wrong.



It's a problem, isn't it? Because there are two HomeController in the program, it doesn't know which one to access! , so we have to add a namespace to the original route based on the error message. Distinguish between two HomeController
New string[] {"_2012_6_16mvc2test.controllers"}

OK, fix it.

Seventh Route test
We can't guarantee that the routing rules we write can be matched to a good one. Here's a tool specifically for analyzing route matching what's called Routedebug
First introduce the DLL and then add the following code to the Application_Start () method in the global file

RegisterRoutes (routetable.routes);
RouteDebug.RouteDebugger.RewriteRoutesForTesting (routetable.routes);

All right, run it!

A simple instance step-by-step help you figure out the routes and areas in the MVC3

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.