The Url rewriting tool provided by ASP. NET MVC3 is a simple implementation process today.
The final result to be implemented: the city pinyin is transferred and resolved in the form of a second-level domain name. As shown in the following figure:
Step 1: Create a UrlProvider. cs file whose class inherits the RouteBase of the routing base class.
| The code is as follows: |
Copy code |
|
After inheriting RouteBase, you need to implement two methods:
Public override RouteData GetRouteData (HttpContextBase httpContext)
{
Throw new NotImplementedException ();
}
Public override VirtualPathData GetVirtualPath (RequestContext requestContext, RouteValueDictionary values)
{
Throw new NotImplementedException ();
} |
Press Ctrl + C to copy the code here. We only implement the above method.
Step 2: implement the GetRouteData method:
| The code is as follows: |
Copy code |
|
Public override RouteData GetRouteData (HttpContextBase httpContext)
{
String controller = "Home ";
String action = "Index ";
String id = "beijing ";
Var data = new RouteData (this, new MvcRouteHandler (); // declare a RouteData and add the corresponding route value
Data. Values. Add ("controller", controller );
Data. Values. Add ("action", action );
// Obtain the request url
Var url = httpContext. Request. Url;
If (url = null)
{
Data. Values. Add ("id", id );
Return data;
}
String virtualPath = url. ToString ();
String param = virtualPath. Replace ("http: //", ""). Split ('.') [0];
If (param. Equals ("www "))
{
Data. Values. Add ("id", id );
Return data;
}
Id = param;
Data. Values. Add ("id", id );
Return data;
} |
Step 3: implement the call to rewrite the route;
Open the automatically generated Global. asax file in the project and modify the RegisterRoutes method:
| The code is as follows: |
Copy code |
|
Public static void RegisterRoutes (RouteCollection routes)
{
Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");
// [Note] the url rewriting call is added here.
Routes. Add (new UrlProvider ());
Routes. MapRoute (
"Default", // Route name
"{Controller}/{action}/{id}", // URL with parameters
New {controller = "Home", action = "Index", id = UrlParameter. Optional} // Parameter defaults
);
} |
Step 4: compile the page processing method;
| The code is as follows: |
Copy code |
|
Public ActionResult Index (string id)
{
Switch (id)
{
Case "beijing ":
ViewBag. CityName = "Beijing ";
Break;
Case "shanghai ":
ViewBag. CityName = "Shanghai ";
Break;
}
String p1 = Request. QueryString ["p1"];
String p2 = Request. QueryString ["p2"];
ViewBag. P1 = p1;
ViewBag. P2 = p2;
Return View ();
} |
Step 5: create a site on IIS and bind the site addresses such as beijing and shanghai