Hello Friends! Hope you are enjoying my articles. Today i will teach you how to use asp.net web API in web application. I assume that you already know what is an API(Application Programming Interface). This tutorial is based on of my clients requirements. He wanted to provide services to his clients using API. So i was asked to develop API in existing web form application. Though i used to develop WEB API in MVC application and it was not hard task for me to fulfill his requirements.
Asp.Net Web API is a framework to develop web API on top of Dot Net Framework.We need some namespaces and assemblies in our existing web application. You can develop a new application from scratch which utilizes WEB API. Follow the steps here:
1. Start Visual Studio and Add an new web form application project.
2. Open Nuget package manager and download these assemblies:
A. System.Web.Http
B. System.Web.Http.WebHost
C. System.Net.Http.Formatting
D. Microsoft.Web.Infrastructure
E. Newtonsoft.Json
Make reference to recently downloaded DLL in project.I already included all required files in downloads.
Web API uses response and request in JSON format by default.
3. Add a new folder to project and name it as “api”. Add a new class file. rename it to “v1Controller”. You may name it according to your choice but don’t forget to suffix “Controller” term.
4. Call namespace System.Web.Http,System.Net.Http and Syste.Net in this class and inherit our controller class from “ApiController” class.
5. Add following web methods in this class:
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { “value1”, “value2” };
}// GET api/<controller>/5
public string Get(int id)
{
return “value”;
}// POST api/<controller>
public void Post([FromBody]string value)
{
}// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}// DELETE api/<controller>/5
public void Delete(int id)
{
}
We are using here GET,POST,PUT and DELETE methods here.
6. Now add a new Global.asax class to project. Add following code snippet to Application Start method in global configuration file.
RouteTable.Routes.MapHttpRoute(
name: “DefaultApi”,
routeTemplate: “api/{controller}/{search}”,
defaults: new { search = System.Web.Http.RouteParameter.Optional });
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
7. Now hit F5 and test web api project.
Download: Web API in Web Application