Introduction to WEBAPI
What is ASP.NET Web API? ASP.NET Web API is a framework which helps to create HTTP services. By using WebAPI, we can create RESTful web services.
RestFul service? REST stands for REpresentational State Transfer.It is an architectural style.
It communicate via HTTP verbs rather than SOAP-based services and do not require XML messages or WSDL service-API definitions.
REST permits different data format such as Plain text, HTML, XML, JSON etc that's why it can be used by multiple clients like mobiles, iphone and tablets browsers etc . Steps to create WebApi Service
1) Step 1: Create New project as given: We have kept project name as MyfirstWebvAPIservice
.
Click on OK button.
Once we click on OK button, we get option to select multiple template. You can select WEBAPI
template as below:
After selecting WebAPI
template, click on OK button. Once you click on OK button, you will get project with default WEB API template.
As in the above mentioned figure, you can see default controller named as ValuesController
has been created which inherits ApiController
. All default created methods are basically used for doing CRUD operations.Below are HTTP methods which we can be used while creating services as per requirement.
GET
POST
DELETE
PUT
POST
To understand basic communication, we will use GET
method first: Below are by default created GET
methods inside ValuesController
controller.
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
public string Get(int id)
{
return "value";
}
Fetch Employee Information by Using Web API Service
Steps: We need to add employee class in model as below . We are currently using only two properties. You can add more properties as per your project requirement.
using System.Linq;
using System.Web;
namespace MyFirstWebAPIService.Models
{
public class Employee
{
public int Employee_ID { get; set; }
public String Employee_Name { get; set; }
}
Once Employee
class is added, now we have to use GET
method with no input parameter to return employee details as below. I have commented existing GET
method with no input parameter method and created new GET
method as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MyFirstWebAPIService.Models;
namespace MyFirstWebAPIService.Controllers
{
public class ValuesController : ApiController
{
public string Get(int id)
{
return "value";
}
[HttpGet]
public List<Employee> GetemployeeList()
{
List<Employee> Employee = new List<Employee>{
new Employee{Employee_ID=123,Employee_Name="Saurabh Sri"},
new Employee{Employee_ID=1567,Employee_Name="Samir Saxena"},
};
return Employee;
}
public void Post([FromBody]string value)
{
}
public void Put(int id, [FromBody]string value)
{
}
public void Delete(int id)
{
}
}
}
I have created employee List
object and assigning hardcoded employee details into object. You can use database to fetch employee details as per your project requirement. Build application as service is ready now.
URL: In normal MVC application, we use MVC controller whle in webAPI, we use APIcontroller
. In APIcontroller
, action methods are nothing but HTTP methods like GET
, POST
, DELETE
, PUT
, etc.
As per requirement, we can use overloading concept also. Default WEBAPI
routing is defined into webconfig file. Please refer to the below figure:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace MyFirstWebAPIService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.EnableSystemDiagnosticsTracing();
}
}
}
- "
api
: It is Prefix with default word "api
" we can change it as per our requirement.
/{controller}
: Name of controller as in our case it is "values
" .
/{id}
": Parameters - optional as per requirement
Note: Here, we do not mention method name because in APIcontroller, action methods are nothing but HTTP methods like GET
, POST
, DELETE
, PUT
.
Test Service By Using Chrome Rest Client Extension as Below
Note: In the above figure, we can see that service is working as per requirement.
Consume Service Through Client Application
To consume webservice, we have to create client application and the below line of code can be used to access employee details from webAPI service:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ReleaseLearning.Models;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
namespace ReleaseLearning.Controllers
{
public class CreateEmployeeController : Controller
{
public ActionResult V_CreateEmployee()
{
Employee Objemployee = new Employee();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:63325/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/Values").Result;
if (response.IsSuccessStatusCode)
{
var EmployeeDetails = response.Content.ReadAsAsync<IEnumerable<Employee>>().Result;
}
return View(Objemployee);
}
}
}