Not written for a long timeArticleNo, it's not too hard to write, but it cannot be written ..
Recently, due to work relations, I reviewed ASP. NET MVC 1.0. Version 2.0 has not been studied.
There are still many shortcomings due to the rapid development of the MVC framework. The routing rule configuration issue is large. First, the routing rule is registered in the application_start () event of the global configuration price global. asax.
Public static void registerroutes (routecollection routes) {routes. ignoreroute ("{resource }. axd/{* pathinfo} "); routes. maproute ("user", // route name "{controller}/{action}/{ID}", // URL with parameters new {controller = "user ", action = "show", id = "0"} // parameter defaults);} protected void application_start () {registerroutes (routetable. routes );}
By default, hard coding greatly reduces the maintenance level in the future. MVC 1.0 does not seem to provide good configuration file-based routing rule settings. So I had to implement it myself. It was not until I wrote this article that I found a better solution.
The following is a custom XML format:
<! -- Default rule --> <maproute name = "default" url = "{controller}/{action}"> <Params> <item key = "controller" default = "article "/> <item key = "action" default = "Index"/> </Params> </maproute> <! -- Display the routing rules of the News list --> <maproute name = "showarticlelist" url = "{controller}/{action}/{typeid}/{pageindex}/{pagesize}"> <Params> <item key = "controller" default = "article"/> <item key = "action" default = "Index"/> <item key = "typeid" default = "1"/> <item key = "pageindex" default = "1"/> <item key = "pagesize" default = "10"/> </Params> </maproute> </maproutes>
Below is allCode
/*************************************** * ********* Author: tang Xiaohua/tension any reprint please be sure to retain this header information copyright all pirated copies required * Email: tension1990@hotmail.com * Description: * Creation Time: 15:17:26 * modification history: **************************************** */using system; using system. collections. generic; using system. LINQ; using system. text; using system. web. routing; using system. web. MVC; using system. XML. LINQ; using Microsoft. CSHARP; Using System. Codedom. compiler; namespace tension. MVC {public static class routehelper {/// <summary> /// register a routing rule from the XML file /// </Summary> /// <Param name = "Routes"> </param> /// <Param name = "prop file"> </param> Public static void register (this routecollection routes, string rule file) {ilist <Route> routes = getroutes (route file); foreach (VAR item in routes) {// The routing rule object OBJ = createobjectformstring (item. tostring (), Item. name); routes. maproute (item. name, // route name item. URL, // URL with parameters OBJ // parameter defaults );}} /// <summary> /// register the route rule from the XML file. The default file is maproute under the root directory of the website. config // </Summary> /// <Param name = "Routes"> </param> Public static void register (this routecollection routes) {register (routes, String. format ("{0} \ maproute. config ", tension. serverinfo. getrootpath ();} // <summary> // String dynamic creation Class Object // </Summary> /// <Param name = "codestring"> </param> /// <Param name = "classname"> </ param> // <returns> </returns> private static object createobjectformstring (string codestring, string classname) {csharpcodeprovider CCP = new csharpcodeprovider (); compilerparameters Param = new compilerparameters (New String [] {"system. DLL "}); compilerresults Cr = CCP. compileassemblyfromsource (para M, codestring); Type type = CR. compiledassembly. getType (classname); return type. getconstructor (system. type. emptytypes ). invoke (null );} /// <summary> /// parse the routing rule from the XML file /// </Summary> /// <Param name = "configfile"> </param> // /<returns> </returns> Private Static ilist <Route> getroutes (string configfile) {stringbuilder sb = new stringbuilder (); console. writeline (sb. tostring (); ilist <Route> routes = N EW list <Route> (); xelement Xe = xelement. load (configfile); # region myregion foreach (VAR item in Xe. elements ("maproute") {// name attribute xattribute xaname = item. attribute ("name"); If (xaname = NULL | string. isnullorempty (xaname. value) {Throw new argumentnullexception ("name! Note: a rule in the routing configuration file lacks the name attribute or the value of the name attribute is a Null String ");} // The URL attribute xattribute urlname = item. attribute ("url"); If (urlname = NULL | string. isnullorempty (urlname. value) {Throw new argumentnullexception ("url! Note: a rule in the routing configuration file lacks the URL attribute or the URL attribute value is a Null String ");} dictionary <string, string> dictparams = new dictionary <string, string> (); # region myregion foreach (VAR pitem in item. element ("Params "). elements ("item") {xattribute itemkey = pitem. attribute ("key"); If (itemkey = NULL | string. isnullorempty (itemkey. value) {Throw new argumentnullexception ("item-> key! Note: a rule in the routing configuration file lacks the item-> key attribute or the item-> key attribute value is an empty string ");} xattribute itemdefault = pitem. attribute ("default"); If (itemdefault = NULL | string. isnullorempty (itemdefault. value) {Throw new argumentnullexception ("item-> default! Note: a rule in the routing configuration file lacks the item-> default attribute or the value of the item-> default attribute is a Null String ");} dictparams. add (itemkey. value, itemdefault. value) ;}# endregion routes. add (new route () {name = xaname. value, url = urlname. value, Params = dictparams}) ;}# endregion return routes ;}} /// <summary> /// routing rule /// </Summary> public class route {public string name {Get; set;} Public String URL {Get; set ;} public dictionary <string, string> Params {Get; set ;} /// <summary> // rewrite the tostring method to generate a dynamic code segment // </Summary> /// <returns> </returns> Public override string tostring () {stringbuilder sb = new stringbuilder (); sb. appendformat ("public class {0}", name); sb. append ("{"); foreach (VAR item in Params) {sb. appendformat ("Public String {0}", item. key); sb. append ("{get {return \" "); sb. append (item. value); sb. append ("\" ;}} ") ;}sb. append ("}"); return sb. tostring ();}}}
The biggest problem encountered during implementation is the dynamic loading of the parameter list. Let's take a look at the following code:
Routes. maproute ("user", // route name "{controller}/{action}/{ID}", // URL with parameters new {controller = "user ", action = "show", id = "0"} // parameter defaults );
This is a hard-coded route rule registration.
The third parameter (New {controller = "user", Action = "show", id = "0"}) is an anonymous object.
How to dynamically build the object becomes a challenge. (Easy to learn)
Try to pass in a dictionary <K, T> but it is useless. ASP. NET parses this parameter to read the object attributes in the form of reflection.
Later I thought of using code segments to dynamically create objects at runtime.
We will make a code snippet similar
Public class default {Public String controller {get {return "article" ;}} Public String action {get {return "Index ";}} public String ID {get {return "0" ;}} Public String page {get {return "1" ;}} Public String size {get {return "10 ";}}}
Input Method
Private Static object createobjectformstring (string codestring, string classname) {csharpcodeprovider CCP = new csharpcodeprovider (); compilerparameters Param = new compilerparameters (New String [] {"system. DLL "}); compilerresults Cr = CCP. compileassemblyfromsource (Param, codestring); Type type = CR. compiledassembly. getType (classname); return type. getconstructor (system. type. emptytypes ). invoke (null );}
You can dynamically create the required parameter objects when running.
Later, you can easily register the route in XML.
Public static void register (this routecollection routes) adds an extension method to the routecollection object
After the corresponding namespace is introduced, it is easy to register.
Improved registration method
Public static void registerroutes (routecollection routes) {routes. ignoreroute ("{resource }. axd/{* pathinfo} ");} protected void application_start () {registerroutes (routetable. routes); // execute the routecollection Extension Method to register the route configuration information routetable in the XML file. routes. register ();}
Code
/Tandly/mvcroutehelper.rar
Suzhou Qing
Tang Xiaohua QQ 1881597 MSN tension1990@hotmail.com
2010 03 10