Objective
In the case of HTTP requests, especially when we use a POST request, we need to convert the requested parameters into URL parameters, such as: a=xxxx&b=xxxx, we are generally accustomed to using entities to transmit parameters, such as the Orderrequest class, This results in the process of converting from an entity to a URL parameter. How entities are converted to URLs with parameters
Public Static classUrlhelper { Public Static stringObjecttoquery<t> ( ThisT obj,BOOLIsaddemptyvalue =true,string=NULL,stringremovefiled =NULL /*Remove that field*/,stringFieldreplace =NULL /*format Old,name*/)whereT:class { if(obj = =NULL) { return ""; } varProperties =obj. GetType (). GetProperties (); varList =Newlist<string>(); foreach(varIteminchproperties) { if(Removefiled! =NULL&& item. Name = =removefiled) { //Remove unnecessary fields Continue; } varProvalue = Item. GetValue (obj,NULL); if((Provalue! =NULL&&!string. IsNullOrEmpty (Provalue.tostring ())) | |isaddemptyvalue) { varValue = provalue! =NULL? Provalue.tostring ():""; Value= value. Replace ("+","%20"); varFiledname =item. Name; //Replace the key name, such as Xxx_name with Xxx[0]. Name if(!string. IsNullOrEmpty (Fieldreplace)) {varArry = Fieldreplace.split ('$'); if(Arry. Length >1) {Filedname= Filedname.replace (arry[0], arry[1]); }} list. ADD (Filedname+"="+value); } } if(!! =NULL) { Switch(by) { Case "ASC": {List= list. (M =m). ToList (); Break; } default: {List= list. OrderByDescending (M = m). ToList (); Break; } } } return string. Join ("&", list); } }The meaning of the specific parameters: 1, Isaddemptyvalue: Whether to remove an entity with a null value, such as: A=&b=xxxx&c=xxxxx, will remove a 2.ORDER BY: Sort alphabetically by ascending or descending order3,removefiled: Remove which fields and values, mainly some entities, although there are assignments, but do not need to pass 4,fieldreplace: Mainly replace the keyword, such as our URL requirements is passagner[0].name, because C # does not support [0]. Name the variable name so that you can name the its first passagener__name, and then the __$[0] This replaces Example
classProgram {Static voidMain (string[] args) {testrequest Testrequest=Newtestrequest () {Contactmobile="133xxxxxxx", Contactuser="Test", Passengers__idnumber="440103xxxxxxxx", Passengers__idtype="1", Passengers__name="Test" }; Console.WriteLine ("{0}", Urlhelper.objecttoquery (testrequest,fieldreplace:"__$[0].", removefiled:"Contactuser")); Console.ReadLine (); } }
The result is:
Conclusion: 1, the entity conversion to the URL is often used, 2,. NET does not support the name of the variable named Passagener[0].name, 3, later can be extended according to their own situation
. NET turning entities into URL parameters