Wednesday, December 16, 2015

ASP.NET Web API 2 Tips and Tricks

Web API Supports RPC(Remote Procedure Call) API and REST API(Representational State Transfer). To simplify this, RPC means action based routing and REST API means Default GET/POST/.... Methods.
REST API offers only method per request type except the Get which comes two times (One for getting Single Record and one for all Records).

Note: You can not use both techniques in One Controller. you can use One only one technique in one controller.

Configuration


By default if you create ASP.NET Web API supported project, it supports REST API method so in the App_Start>WebApiConfig.cs file has following rout configuration,




 config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

Now There are situations while you need action(Method of Controller) based routing. you need to first change the Route to,

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );


RPC/Action Based Routing


public class testController : ApiController
    {

GET Requests

        /*GET   /api/test/GetBook?id=56&name='testbook'      */

        [HttpGet]
        [ActionName("GetBook")]
        public string Book(int id, string name)
        {
            return "book";
        }
///////////////////////////////////////////////////////////////////////////////////////////////////////////

        // GET /api/test/GetCustomer?id=56

        [HttpGet]
        [ActionName("GetCustomer")]
        public string Customer(int id)
        {
            return "value";
        }


POST Requests

////////////////////////////////////////////////////////////////////////////////////////////////
        /* POST api/test/AddFirst?name=5   */  Right

        /* POST api/test/AddFirst  
        Raw Form Data in Postman is 5 */      Wrong

       

        [HttpPost]
        [ActionName("AddFirst")]
        public void First(int name)
        {
            int i = 0;
        }
///////////////////////////////////////////////////////////////////////////////////////////////////
          /* POST api/test/AddFourth?name=5   */  Right

        /* POST api/test/AddFourth  
        Raw Form Data in Postman is 5 */      Right

        [HttpPost]
        [ActionName("AddFourth")]
        public void Fourth([FromBody]int name)
        {
            int i = 0;
        }

//////////////////////////////////////////////////////////////////////////////

  /* POST api/test/AddSecond   
        Raw Form Data in Postman is      {ID:1, Name:'kaka'}             */      

        [HttpPost]
        [ActionName("AddSecond")]
        public void Second(UserClass pp)
        {
            int i = 0;
        }


////////////////////////////////////////////////////////////////////////////

  /* POST api/test/AddThird?token='mytokenvalue'

        Raw Form Data in Postman is      {ID:1, Name:'kaka'}             */  Right    

 /* POST api/test/AddThird

        Raw Form Data in Postman is      {ID:1, Name:'kaka'}   'mytokenvalue'          */     Wrong
// As POST cannot retrieve two values from the body so the simple values can be sent through query string as shows in the "right" way to call API. The other best way to use this is like in the next example


        [HttpPost]
        [ActionName("AddThird")]
        public void Third(string token, UserClass user)
        {
            int i = 0;
        }

////////////////////////////////////////////////////////////////////////////  

 /* POST api/test/AddThird

        Raw Form Data in Postman is      {ID:1, Name:'kaka', Token: 'mytokenvalue'}           */   
// As POST cannot retrieve two values from the body so we will treat it as single object. We will create a new class on C# side that has ID, Name and Token. 


        [HttpPost]
        [ActionName("AddThird")]
        public void Third( UserTokenClass utc)
        {
            int i = 0;
        }

////////////////////////////////////////////////////////////////////////////  

// There is one more option to use dynamic type variable in c#. 

 /* POST api/test/AddThird

        Raw Form Data in Postman is      {User: {ID:1, Name:'kaka'}, Token: 'mytokenvalue'}           */   

        [HttpPost]
        [ActionName("AddThird")]
        public void Third( dynamic utc)
        {
            string token = utc.Token;
            UserClass uc = new UserClass();
            uc.ID = utc.User.ID;
            uc.Name = utc.User.Name; 
            int i = 0;
        }

      





}


No comments:

Post a Comment