Implement Web API in Existing Web Form Application

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.

Implement Web API

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.

Implement Web API

Step 3

Select "Web API controller" from the template and give an appropriate name to it.

In my case I used “StudentController”.

Implement Web API

Step 4

Open the Global.asax page of the application and add the following code to the Application_Start() event.

  1. RouteTable.Routes.MapHttpRoute(  
  2.             name: "DefaultApi",  
  3.             routeTemplate: "api/{controller}/{id}",  
  4.             defaults: new { id = System.Web.Http.RouteParameter.Optional }  
  5.             );

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.

  1. 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.

  1. public class StudentController : ApiController  
  2. {  
  3.     // GET api/<controller>  
  4.     public IEnumerable<string> Get()  
  5.     {  
  6.         return new string[] { "value1""value2" };  
  7.     }  
  8. }

After running the application in a browser, we will get the following output.

Implement Web API

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.


Similar Articles