Monday, April 30, 2018

Parameter Binding or Model Binding in ASP.NET Web API

The process of setting values to the parameter of  WEB API method is called parameter binding and In parameter binding, it takes an HTTP request and converts it into .Net types so that you can able to set action parameters.

The generic rules or default behavior of WEB API parameter binding: 
·         If parameter is simple .Net primitive types (integer, bool, decimal etc.) it try to get from HTTP Request URI.
·         If parameter is Complex Type, It read the value from http request http request body. 



Here is HTTP Request URI, Which is being used to call to Web API to get project information.


public class ProjectApiController : ApiController
    {

        public ProjectApiController()

        {
        }

       [HttpGet]

        public Project GetProject(int projectId)

        {

            return Repository.GetProperty(projectId);
        }
   }


GetProject is a web api method that has one simple type parameter – (int projectId) and by default, simple type parameter value will be set from URI [?projectId=2] , so its value should be 2 .

By using [FromUri] attribute, the parameter value should be read from Http Request Uri.


       [HttpGet]

        public Project GetProject([FromUri] int projectId)

        {

            return Repository.GetProperty(projectId);

        }


By using [FromBody] attribute, the parameter value should read from Http Request Body.

       [HttpGet]

        public Project GetProject([FromBody] int projectId)

        {
            return Repository.GetProperty(projectId);             
         }


By default, the value of complex type of parameter should read from Body but you can set value from Uri by using [FromUri] attribute 



SearchParameter as complex type: 
  
public class SearchParameter
    {

        public int PageNumber { getset; }

        public int PageSize { getset; }

        public string Name { getset; }

        public string Location { getset; }

    }

               [HttpGet]

    public HttpResponseMessage Get([FromUri]SearchParameter filter)

        {

        }




Other related topics:
  1. ASP.NET Web API Caching
  2. Steps To Improve ASP.NET Web API Performance
  3. 4 Simple Steps To Create ASP.NET Web API
  4. Parameter Binding or Model Binding in ASP.NET Web API
  5. The Life-cycle of an ASP.NET Web API
Thanks for visiting!! 



No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...