With ASP. NET MVC is used to, the recent project started using ASP., there are a lot of Ajax method calls, there are two ways to deal with it before:
- Switch Case: The method is less OK, if a lot, it is too painful, and the method heap in a piece, also not beautiful
- Anonymous method: Method reuse is not good, vs code is not easy to collapse
I have recently studied the use of reflection methods to do all the public methods in the class through reflection to find the dictionary, the call to match the dictionary key, see if there is this method.
Here is my method of writing, this method I summarize the following advantages:
- Do not write a large number of judgment statements, concise
- Method can be reused
- Can focus on some things, such as pre-call monitoring, processing, exception handling;
- If there are different implementations, you can invoke implementations of different interfaces (virtual methods) (I'm here for the sake of convenience, no interfaces)
But I do not know this write, will not have performance loss, whether there is a place to optimize, welcome to the guidance.
Public classNewservices:ihttphandler {Private Static ReadOnlyidictionary<string, methodinfo> Services =Newdictionary<string, methodinfo>(stringcomparer.ordinalignorecase); Public voidProcessRequest (HttpContext context) {varAction = context. request["Action"]; if(Action. Isnotnullandwhitespace () &&Services.containskey (Action)) { Try{services[action]. Invoke (NewNewservicesapi (context),NULL); } Catch(Exception ex) {context. Writejson (NewJsonresultinfo (). SetError (ex. Message)); } } Else{context. Writejson (NewJsonresultinfo (). SetError ("{0} method does not exist! ". Formatwith (action)); } } Staticnewservices () {services.clear (); varMethods =typeof(NEWSERVICESAPI). GetMethods (BindingFlags.Public |bindingflags.instance); foreach(varMinchmethods) {Services.add (M.name, M); } } Public BOOLisreusable {Get{return false; } } } Internal classNewservicesapi {PrivateHttpContext context; PrivateHttpRequest Request; PrivateHttpResponse Response; PublicNewservicesapi (HttpContext context) { This. Context =context; Request=context. Request; Response=context. Response; } Public voidTest () {Response.Write ("Test"); } }
ASP. NET General Handler small optimization