ASP.NET Web API

About ASP.NET Web API

  • The ASP.NET Web API is an extensible framework for building HTTP based services that can be accessed in different applications on different platforms such as web, windows, mobile etc. It works more or less the same way as ASP.NET MVC web application except that it sends data as a response instead of html view.
  • it only supports HTTP protocol.
  • It is built on top of ASP.NET and supports ASP.NET request/response pipeline
  • It maps HTTP verbs to method names.
  • It supports different formats of response data. Built-in support for JSON, XML, BSON format.
  • It can be hosted in IIS, Self-hosted or other web server that supports .NET 4.0+.
  • ASP.NET Web API framework includes new HttpClient to communicate with Web API server. HttpClient can be used in ASP.MVC server side, Windows Form application, Console application or other apps.


API Version:

Web API 1.0                 -  .NET Framework 4.0
Web API 2 (Current) -  .NET Framework 4.5

Creation of web api application already discussed in my blog post. For getting idea on creation of web api please click on the below link.

http://c-sharpcodedestination.blogspot.in/2017/01/how-to-build-aspnet-mvc-web-api-solution.html

Web API Request/Response Data Formats: xml, json, html, jpeg

Parameter Binding:

Here, we will learn how Web API binds HTTP request data to the parameters of an action method. Web API binds action method parameters either with URL's query string or with request body depending on the parameter type. Parameters can be either primitive type or complex type.

Primitive Type Parameter:

Get Action Method:

For passing single parameter value in Get Action Method:

The HTTP Get request will be :

http://localhost/api/employee?id=1

then value of id parameter will be 1.

Then in api controller write this Get() method:

public class EmployeeController : ApiController
{
    public Employee Get(int id)
    {
           
    }
}

For passing multiple parameters in Get Action Method :

The HTTP Get request will be :

http://localhost/api/employee?id=1&name=hari

then value of id parameter will be 1 and the name parameter will be hari.

Then in api controller write this Get() method:

public class EmployeeController : ApiController
{
    public Employee Get(int id, string name)
    {
           
    }
}

Post Action Method:

For passing parameters value in Post Action Method:

The HTTP Post request will be :

http://localhost/api/employee?id=1&name=hari

then value of id parameter will be 1 and name will be hari.

Then in api controller write this Post() method:

public class EmployeeController : ApiController
{
    public Employee Post(int id, string name)
    {
           
    }
}


Complex Type Parameters:

Use this common class file in your HTTP action method

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Get Action Method :

For passing Employee object in Get Action Method :

The HTTP Get request will be :

http://localhost/api/employee

in request body just write this below code

{
id=1,
name='hari'
}

Then in api controller write this Get() Method:

public class EmployeeController : ApiController
{
    public Employee Get(Employee emp)
    {
           
    }
}

Post Action Method :

For passing Employee object in Post Action Method :

The HTTP Post request will be :

http://localhost/api/employee

in request body just write this below code

{
id=1,
name='hari'
}

Then in api controller write this Post() Method:

public class EmployeeController : ApiController
{
    public Employee Post(Employee emp)
    {
           
    }
}

Post Method with Primitive and Complex Type Parameters :

For passing Employee object and a parameter in Post Action Method :

The HTTP Post request will be :

http://localhost/api/employee?age=12

in request body just write this below code

{
id=1,
name='hari'
}

Then in api controller write this Post() Method:

public class EmployeeController : ApiController
{
    public Employee Post(int age, Employee emp)
    {
           
    }
}


[FromUri] and [FromBody] :

Use [FromUri] attribute to force Web API to get the value of complex type from the query string and [FromBody] attribute to get the value of primitive type from the request body, opposite to the default rules.

Example: FromUri

In api controller write this Get() Method:

public class EmployeeController : ApiController
{
    public Employee Get([FromUri] Employee emp)
    {

    }
}

The HTTP Get request will be :

http://localhost/api/employee?id=1&name=hari

Web API by default extracts the value of complex type from request body but here we have applied [FromUri] attribute.

Example: FromBody

In api controller write this Post() Method:

public class EmployeeController : ApiController
{
    public Employee Post([FromBody] string name)
    {

    }
}

The HTTP Get request will be :

http://localhost/api/employee

in request body write this below code for passing parameter value:

{
name:'hari'
}


Action Method Return Type:

The Web API action method can have following return types.

1. Void
2. Primitive type or Complex type
3. HttpResponseMessage
4. IHttpActionResult

1. Void :

It can have void return type.

Example: Void Return Type

public class EmployeeController : ApiController
{
    public void Delete(int id)
    {
        DeleteEmployeeFromDB(id);
    }
}

It will send 204 "No Content" status code as a response when you send HTTP DELETE request.

2. Primitive or Complex Type:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class EmployeeController : ApiController
{
    public int GetId(string name)
    {
        int id = GetEmployeeId(name);
 
        return id;
    }

    public Employee GetEmployee(int id)
    {
        var emp= GetEmployeeFromDB(id);
 
        return emp;
    }
}

HttpResponseMessage:

Here you can configure a response your way. You can set the status code, content or error message as per your requirement.

Example:

public HttpResponseMessage Get(int id)
{
    Employee emp = GetEmployeeFromDB(id);

    if (emp == null) {
        return Request.CreateResponse(HttpStatusCode.NotFound, id);
    }

    return Request.CreateResponse(HttpStatusCode.OK, emp);
}

if there is no employee with specified id in the DB then it will return HTTP 404 Not Found status code, otherwise it will return 200 OK status with employee data.

IHttpActionResult:

Here you can create your own class that implements IHttpActionResult or use various methods of ApiController class that returns an object that implement the IHttpActionResult.

public IHttpActionResult Get(int id)
{
    Employee emp = GetEmployeeFromDB(id);
         
    if (emp == null)
    {
        return NotFound();
    }

    return Ok(emp);
}

Post a Comment

1 Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete