Implement Web API in Web Form Application
I am a little interested in the Web API and talking much about it. Recently one of my friends asked me, Hey! I would like to use the Web API but my application is a pure Web Form application. Shall I use the Web API in a Web Form application?
The truth to be told, I also had no idea how to implement the Web API in a Web Form application before writing this article. I made a little search in Google and developed a solution. Yes, it’s quite possible to use the Web API in a Web Form application and in this article I am interested in implementing it practically.
Step 1
Create one ASP.NET Web Form application
As we said, we will implement the Web API in a Web Form application. So create a new Web Form application.
Step 2
Once the solution has been created, create just one empty folder named controller and right-click on that to add one new item.
Step 3
Select "Web API controller" from the template and give an appropriate name to it.
In my case I used “StudentController”.
Step 4
Open the Global.asax page of the application and add the following code to the Application_Start() event.
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
Here we are adding a route for the Web API application in the Web Form application. The “api” is the default string of the URL. It’s very similar yo MVC routing.
For that we need to include the following namespace in the Global.asax page.
using System.Web.Http;
Step 5
Implement the Get() method within the Student controller.
Here I have kept the default template of the Get() method as it is.(I am a little lazy fellow.). Let’s consider this is our Get() method within the student controller that will return the name of a few students.
public class StudentController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
After running the application in a browser, we will get the following output.
Conclusion
I know this article is not informative but is helpful for developers that want to implement the Web API in their existing Web Form application.