Use reflection + jquery in ashx to easily process Ajax with demo source code

Source: Internet
Author: User

Due to the emergence of jquery, compile JSCodeIt has become abnormal and common, and now the Web is full of Ajax. You can write a web without Ajax on your own.

Of course, in. the development of the control mode in net has become more universal: jquery + Ajax + ashx is more suitable for the development of some small applications, simple, free

Since we were too young at that time, we were just starting the development of this mode when we were sending an Ajax request to an ashx page. As a result, we can imagine that there were dozens of optical ashx files in a small permission system, in addition, the file names are similar and tragic.

Later, I became smarter and put all requests of the same category into an ashx file. Each request sends a request flag to call the corresponding request method through a switch. Of course, this is much better than the original one. At least there are not so many ashx files, but every time you create a new file, you have to add the switch method, what's even more shameful is that every time you add, delete, or modify a request, you have to modify the hateful switch statement.

Later I learned about reflection, and I knew that I could use reflection to call Methods dynamically. I thought it was a good idea. I checked the relevant information and wrote the framework in a few minutes. Then I searched Baidu, leo, there are so many such issuesArticleI didn't want to write this article any more, but I tried to write code and write it myself, and this is more convenient and practical than on the Internet.

The following is a detailed explanation of the handler's backbone chicken class.

First, define several default parameters in the chicken class.

/// <Summary> /// specify the HTTP request type. Specify the get or POST method for receiving the action method name. /// </Summary> protected namevaluecollection _ httpreuqest = httpcontext. current. request. form; /// <summary> /// specify the return header /// </Summary> protected string _ contenttype = "text/plain "; /// <summary> /// specify the parameter name for receiving the action method /// </Summary> protected string _ actionname = "action ";

It mainly defines the default Request Method "get" or "Post". Of course, the default value is "Post". It is relatively secure and many people use it. Of course, this request method can be removed from the subclass.

There is also the Request Response Header, which is clearly written in the comments of the parameter code of the method name.

The following is the core code of the dynamic call method (here I will give a reflection connection related knowledge, I don't know)

// Obtain the method name string action = This. _ httpreuqest [This. _ actionname] based on the specified request type; If (! String. isnullorempty (Action) {// public access is required for non-static instance obtaining methods. case-insensitive methodinfo = This. getType (). getmethod (action, bindingflags. instance | bindingflags. public | bindingflags. ignorecase); If (methodinfo! = NULL) {// call method methodinfo. invoke (this, null);} else {Throw new applicationexception (string. format ("method {0} Not Found", Action) ;}} else {Throw new argumentnullexception ("the call method parameter is not found or the method name is blank ");}

The core code is simple enough. In fact, the core code is to obtain the Method Instance. Of course, this method is convenient.

Let's look at the code for getting the Method Instance.

It is mainly used to obtain non-static, publicly accessible, and case-insensitive methods in the class. Of course, if you are not sure that other methods are also called by Ajax cross-origin, you can set the access permission of this method to private or protected. If you are still not at ease, you can customizeAttribute features are added to the method, but I don't feel necessary here.

Let's take a look at all the code for chicken.

/// <Summary> /// the base class of the handler request uses this class to dynamically call the Request Method // </Summary> public class handlerbase: ihttphandler {// <summary> // specify the HTTP request type. Specify the receiving method of the action method name. Get or post /// </Summary> protected namevaluecollection _ httpreuqest = httpcontext. current. request. form; /// <summary> /// specify the return header /// </Summary> protected string _ contenttype = "text/plain "; /// <summary> /// specify the parameter name for receiving the action method /// </Summary> protected string _ actionname = "action "; // obtain the current HTTP context protected httpcontext {get {return httpcontext. current; }} public void processrequest (httpcontext context) {context. response. contenttype = This. _ contenttype; try {// The dynamic call method. Of course, you can add the same domain name request to determine whether this. dynamicmethod ();} catch (ambiguousmatchexception AMEX) {This. printerrorjson (string. format ("multiple methods are found based on this parameter {0}", Amex. message);} catch (argumentexception argex) {This. printerrorjson ("parameter exception" + argex. message);} catch (applicationexception apex) {This. printerrorjson (" Program Exception "+ apex. message) ;}# region dynamic call method /// <summary> /// dynamic call method /// </Summary> private void dynamicmethod () {// obtain method name string action = this based on the specified request type. _ httpreuqest [this. _ actionname]; If (! String. isnullorempty (Action) {// public access is required for non-static instance obtaining methods. case-insensitive methodinfo = This. getType (). getmethod (action, bindingflags. instance | bindingflags. public | bindingflags. ignorecase); If (methodinfo! = NULL) {// call method methodinfo. invoke (this, null);} else {Throw new applicationexception (string. format ("method {0} Not Found", Action) ;}} else {Throw new argumentnullexception ("the call method parameter is not found or the method name is blank ");}} # endregion # handle json printing by region /// <summary> /// print the JSON file with an exception /// </Summary> /// <Param name = "MSG"> </param> protected void printerrorjson (string MSG) {This. printjson ("error", MSG );} /// <summary> /// print the successfully processed JSON // </Summary> /// <Param name = "MSG"> </param> protected void printsuccessjson (string MSG) {This. printjson ("success", MSG );} /// <summary> /// print JSON /// </Summary> /// <Param name = "state"> </param> /// <Param name = "MSG"> </param> protected void printjson (string state, string MSG) {This. context. response. write ("{\" state \ ": \" "+ state +" \ ", \" MSG \ ": \" "+ MSG + "\"}");} # endregion public bool isreusable {get {return false ;}}}

Just write a few test ashx pages to inherit the base class.

 
/// <Summary> /// get test of the general handler /// </Summary> public class gethandler: handlerbase {public gethandler () {// modify the request to get base. _ httpreuqest = base. context. request. querystring;} // <summary> // addition operation // </Summary> Public void add () {int A = convert. toint32 (_ httpreuqest ["A"]); int B = convert. toint32 (_ httpreuqest ["B"]); printsuccessjson (A + B ). tostring ();} // <summary> // subtraction operation // </Summary> private void minus () {int A = convert. toint32 (_ httpreuqest ["A"]); int B = convert. toint32 (_ httpreuqest ["B"]); printsuccessjson (a-B ). tostring ());}}

The following post type

/// <Summary> /// test the post general handler /// </Summary> public class posthandler: handlerbase {public posthandler () {// modify the request to get base. _ httpreuqest = base. context. request. form ;}//< summary> /// Multiplication operation /// </Summary> Public void multiply () {int A = convert. toint32 (_ httpreuqest ["A"]); int B = convert. toint32 (_ httpreuqest ["B"]); printsuccessjson (A + B ). tostring ();} // <summary> // subtraction operation // </Summary> Public void minus () {int A = convert. toint32 (_ httpreuqest ["A"]); int B = convert. toint32 (_ httpreuqest ["B"]); printsuccessjson (a-B ). tostring ());}}

It's easy to understand. The front-end HTML page will not be pasted.

If you really don't understand what you are looking at, please slam me to the source code below.

if you have any design mistakes, please leave a message to correct them and make progress together.

Related Article

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.