Use MVC, unity to make service restful

Source: Internet
Author: User
Tags httpcontext

now that the demand for mobile devices is growing, one way to meet their data requirements is to achieve restful, out-of-the-way back-office support. In Microsoft's implementation, we need to build a WEB API project with VS, and use System.Web.Http to publish your own control.
public class Outvaluescontroller:apicontroller    {        //Get api/values public        ienumerable<string> Get (        {            return new string[] {"value1", "value2"};        }        Get API/VALUES/5 public        string get (int id)        {            return ' value ';        }        Post api/values public        void post ([frombody]string value)        {        }        //PUT API/VALUES/5        Public void Put (int id, [frombody]string value)        {        }        //delete API/VALUES/5 public        void Delete (int id)        {        }    }

This implementation requires the inheritance of Apicontroller, which is difficult to implement in many of the systems that already have a lot of service, and there are restrictions on controller and service.

Describes two types of restful service that are implemented using MVC, unity, and reflection.

The first kind of modification MICROSOFT.WEB.MVC realization;

First use a controller to implement restful, modify its actioninvoker to intercept the call.

public class Apihelpercontroller:controller    {        //Microsoft's Controlleractivator activates the Controller, the parameterless constructor is executed! Public        Apihelpercontroller ()        {            base. Actioninvoker = new Myactioninvoker ();        }    }
Then, the following is chaotic, the overall is to obtain the controller, the method name from the ControllerContext, using unity according to the controller name to obtain an instance, using reflection to invoke invoke directly, the result Implemented with JSON.

  public override bool Invokeaction (ControllerContext ControllerContext, string controllername)         {           //Find action based on the action name and execute it, including the rendering of the view and the execution of the various features applied on the action &nbsp ;          //return false; Execution failure            //return true;    //execution Success            //return base. Invokeaction (ControllerContext, ActionName);            Type mappedtype;    & nbsp       Mappedtype = Unityconfig.getconfiguredcontainer (). Registrations.singleordefault (n = n.name = = controllername). mappedtotype;                      Object service = Unityconfi G.getconfiguredcontainer (). Resolve (Mappedtype, new microsoft.practices.unity.resolveroverride[] {});           // Object Service =unityconfig.gettargetservice (ConTrollername);            String methodName = ControllerContext.RequestContext.RouteData.GetRequiredString ("id");            MethodInfo method = Service. GetType (). GetMethod (methodName);            NameValueCollection C = controllercontext.requestcontext.httpcontext.request.querystring;            string[] Targetparams = new string[c.count];            C.copyto (targetparams, 0);    &nbsp ;      //Get parameter list of specified method               parameterinfo[] Paramsinfo = Meth mdl GetParameters ();            httpresponsebase response = controllercontext.httpcontext.response;            JavaScriptSerializer serializer = new JavaScriptSerializer ();            if (paramsinfo.length! = c.count)       &nbsp     {                response. Write ("Parameter mismatch! ");                return true;           }  & nbsp         object[] finalparams = new object[c.count];            for (int i = 0; i < C.count; i++)             {                Type ttype = params Info[i].  parametertype;               //If it is a value type, or string                   if (Ttype.equals (typeof (String)) | | (!ttype.isinterface &&!ttype.isclass))                 {                  &N Bsp Change parameter type                       Finalparams[i] = Convert.change Type (TargEtparams[i], Ttype);               }            &NB Sp   Else if (ttype.isclass)//If it is a class, convert its JSON string to object                   {                     Finalparams[i] = Newtonsoft.Json.JsonConvert.Deseria Lizeobject (Targetparams[i], ttype);               }        &N Bsp  }            Object data = method. Invoke (service, Finalparams);            response. Write (serializer. Serialize (data);            return true;       }





Use MVC, unity to make service restful

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.