In-depth understanding of ASP. net mvc (4)

Source: Internet
Author: User
ArticleDirectory
    • Custom routebase
    • Custom iroutehandler

Series directory

Datatokens and areas mechanisms

So farRouteOnly objects are leftDatatokensThe property is not involved. In fact, thisAreasThe core of the mechanism.

DatatokensIt is actuallyRoutevaluedictionary, In useMaprouteThe method is constructed inRouteWhen constructing, you can pass a namespaces string array. this parameter is constructedRouteThe datatokens ["namespaces"] of the object. Its value isThe MVC framework is used first to find the corresponding controller in the corresponding namespace.. If the controller can be found in the specified namespace, it does not matter even if the Controller with the same name in other namespace (case sensitive; if the controller is not found in the specified namespaceProgramCentralized search. If the Controller with the duplicate name appears, multiple Matching errors will occur. This behavior is implemented by defacontrocontrollerfactory. The defaultcontrollerfactory will be analyzed later.

The areas mechanism is like this: different areas can have the same name controller, that is, the Controller name can be repeated! In this way, the entire web application can be divided into several modules by function. Each module is an area and each area is independent of each other, A developer can define a URL or controller independently without affecting other areas.

For example, if you have two modules: Administrator and user, you may need the following URL:

Admin/home/Index

User/home/Index

Therefore, you can use the area generation template integrated with vs to create two areas: Admin and user. The two developers are responsible for the development respectively. Both of them need to use the homecontroller and index methods, with the areas mechanism, homecontroller is put into two different namespaces, which will not conflict.

At this point, you may have a vague understanding of the relationship between the areokens and areas mechanisms. What did vs do when creating areas?

1. The controller will be placed in a namespace in each area, for example, myappname. Areas. admin. controllers;

2. Create an arearegistration inheritance class for each area. If it is admin, the area will be adminarearegistration. In this class, override the areaname attribute and the registerarea method:

Public override void registerarea (arearegistrationcontext context) {context. maproute ("admin_default", "admin/{controller}/{action}/{ID}", new {Action = "Index", id = urlparameter. optional });}

You can see that the maproute method is also called to register a route in the registerarea method. Note thatMaprouteEvenOperate a global route tableBut its implementation is slightly different:

1. First, the URL pattern is set to start with the name of area. This is necessary. After all, this URL pattern will be placed globally;

2. It sets datatokens ["namespaces"] To the namespace of the current area, for example, myappname. Areas. admin .*. The result is that when a request arrives, defaultcontrollerfactory takes precedence over the namespace to find the controller. A datatokens ["usenamespacefallback"] is added and set to false.When and only whenIf a controller is required in the configured namespace is displayed, the operation can be successful. The controller with the same name in other namespace will be invalid;

3. At last, a key value named datatokens ["area"] will be added and set to the name of the current area. This is used when the reverse ing (outbounding) URL is used.Therefore, the "area" key in MVC has a special purpose, so it cannot be used for URL pattern parameters.

Note that there is a conflict in the areas mechanism. Because there is only one route table, if the current URL is mapped to "root area" (that is, in the global domain), the Controller will be searched from all the namespaces currently, at this time, it is possible to find multiple matches. The solution is to set a priority namespace for datatokens when setting a route in globla. asax. CS.

 

 

Further expansion

After a deep understanding of the routing mechanism, you can customize the routing mechanism.

Custom routebase

With the previous analysis, we can know that during inbound, route (inherited from routebase) needs to provide a routedata. Therefore, routebase defines the getroutedata method, which can be implemented by ourselves. At the same time, the getvirtualpath method is used for outbound. Therefore, you only need to implement these two methods to implement a routebase. For example, if you want to transform an old website into a new MVC-based architecture and do not want to invalidate the original URL, a simple solution can be as follows:

Public class legacyurlsroute: routebase {// in practice, you might fetch these from a database // and cache them in memoryprivate static string [] legacyurls = new string [] {"~ /Articles/May/zebra-danio-health-tips.html ","~ /Articles/velociraptorcalendar.pdf ","~ /Guides/Tim. smith/buildyourownpc_final.asp "}; Public override routedata getroutedata (httpcontextbase httpcontext) {string url = httpcontext. request. apprelativecurrentexecutionfilepath; If (legacyurls. contains (URL, stringcomparer. ordinalignorecase) {routedata RD = new routedata (this, new mvcroutehandler (); Rd. values. add ("controller", "legacycontent"); Rd. values. add ("action", "handlelegacyurl"); Rd. values. add ("url", URL); Return RD;} elsereturn NULL; // not a legacy URL} public override virtualpathdata getvirtualpath (requestcontext, routevaluedictionary values) {// This route entry never generates outbound urlsreturn NULL ;}}

 

Custom iroutehandler

Generally, in the MVC Framework, iroutehandler is implemented by mvcroutehandler, the entry of this MVC framework. However, we can define an iroutehandler by ourselves. This can be considered when we need to optimize some requests. Because the custom implementation of iroutehandler means that the MVC Framework will be ignored. For example, the following implementation:

 
Public class helloworldhandler: iroutehandler {public ihttphandler gethttphandler (requestcontext) {return new handler ();} private class handle: ihttphandler {public bool isreusable {get {return false ;}} public void processrequest (httpcontext context) {context. response. write ("Hello, world! ");}}}

Labor fruit, reproduced please indicate the source: http://www.cnblogs.com/P_Chou/archive/2010/11/15/details-asp-net-mvc-04.html

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.