With the release of ASP.NET MVC 4 one of the exciting features packed in the release was ASP.NET Web API. In a nutshell, ASP.NET Web API is a new framework for creating HTTP services that can reach a broad range of clients including browsers and mobile devices. ASP.NET Web API is also an ideal platform for building RESTful services.

Microsoft shipped “ASP.NET and Web Tools 2012.2” update sometime in February 2013. This included updated ASP.NET MVC Templates, ASP.NET Web API, SignalR and Friendly URLs. So if you take the latest you get all the latest bits ASP.NET has to offer so far. Rest of this post assumes that you have installed the 2012.2 bits. I assume you know the Web API fundamentals like API Controller,  Action and Route configuration as I wont get into discussing those.

In this post, we will see how Web API can be created in a Web Form application or project. I will be using Visual Studio Express 2012 for Web as my IDE for this post.

Create ASP.NET Web Form Project:

To start out with, create a empty “ASP.NET Empty Web Application” or “ASP.NET Web Forms Application”. Both of these templates are Web Forms based. So doesn’t matter which one you choose. For the sake of the demo I will choose ASP.NET Empty Web Application. Fire up a Visual Studio Express 2012 for Web, File > New Project > ASP.NET Empty Web Application and give a name to the project.

imageFig 1: New Project Dialog

Visual Studio will create the project and you should have the infrastructure ready. And here is how the solution will look like:

Fig 2: Solution Explorer

Adding a Web API Controller:

Since Web API is kind of API we are building lets bring in some best practice here. It is good to have a folder created with the name “Api” and store all your Web API controllers here. With the latest release of ASP.NET, you can create Controllers in any folder you like. So go ahead and create a new folder and name it API. Here is how the Solution Explorer will look like:

Fig 3: Api Folder

Now lets add a Web API Controller. Right click on Api folder, select Add > New Item. You will find a new Item Template called “Web API Controller Class”. Select Web API Controller Class Item. Note that Visual Studio names the class as ValuesController1.cs – you can rename it to ValuesController. Make the changes and click Add.

Fig 4: Adding Web API Controller Class

Here is the glimpse of the code inside ValuesController class provided by default:

Fig 5: Values Controller Class

There is one magic Visual Studio does under the hood when you add a Web API Controller class. It adds the following packages which is required for making the Web API work:

  • Microsoft.AspNet.WebApi
  • Microsoft.AspNet.WebApi.Client
  • Microsoft.AspNet.WebApi.Core
  • Microsoft.AspNet.WebApi.WebHost
  • Microsoft.Net.Http
  • Newtonsoft.Json

You can see that there is a packages.config file added to the solution and it is used by Nuget package manager to keep track of the packages. The above packages make it possible for Web API to be hosted within the Web Forms application or project. So, is this all to make the Web API run – well not yet. Web API works with the routes and we have not yet configured the routing engine to grab the request and see if it is web api request. Lets do that in next section.

Setting up Web API Routes:

One thing you will notice in the solution is – it does not contain a Global.asax file. Well that’s why the name of the template “ASP.NET Empty Web Application” its literally empty and you need to add things needed manually. So first lets go ahead and add a Global.asax. Right click on the project, select Add > New Item > Global Application Class. You will get the blank Global.asax i.e. the class will have all the event handler added up but empty. The event handler which is of importance for us is Application_Start. Lets now configure the Http Routing. As a best practice create a new folder called App_Start at the root of the project. Add a new class, call it WebApiConfig.cs and make it a static class. Idea behind naming the folder as App_Start is that, codes in this folder are the first to be called or executed when the app starts. So here is how the solution explorer looks like now:

Fig 6: Solution Explorer

Now add the following code to WebApiConfig.cs. We are creating a static method called Register and it will register the Http routes for the application:

   1: public static void Register(HttpConfiguration config)

   2: {

   3:     config.Routes.MapHttpRoute(

   4:         name: "DefaultApi",

   5:         routeTemplate: "api/{controller}/{id}",

   6:         defaults: new { id = RouteParameter.Optional }

   7:     );

   8: }

Listing 1: WebApiConfig Register method

What we are doing in Register method is:

  • Get the HttpConfiguration object
  • Use the Routes table to configure routes
  • Map a Http Route to our API by providing a pattern
  • Default pattern is to look for “api/{controller}/{id} – where {id} is optional

Here is the complete code of WebApiConfig.cs file:

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Web;

   5: using System.Web.Http;


   7: namespace WebAPIinWebForms.App_Start

   8: {

   9:     public static class WebApiConfig

  10:     {

  11:         public static void Register(HttpConfiguration config)

  12:         {

  13:             config.Routes.MapHttpRoute(

  14:                 name: "DefaultApi",

  15:                 routeTemplate: "api/{controller}/{id}",

  16:                 defaults: new { id = RouteParameter.Optional }

  17:             );

  18:         }

  19:     }

  20: }

Listing 2: WebApiConfig class

Now, this is just a definition but where do we actually call it. Remember we added a Global.asax file – we will call the Register method from the Application_Start event handler. Here is the code to do that:

   1: protected void Application_Start(object sender, EventArgs e)

   2: {

   3:    WebApiConfig.Register(GlobalConfiguration.Configuration);

   4: }

Listing 3: Global.asax Application_Start event handler

And we have a Web API created in Web Forms project now. Next lets see how to test it out.

Testing Web API:

At this moment if you build and run the project, browser may show you 403 and that is expected as we do not have an Default.aspx or index.html. Don’t worry as we are interested in testing the API controller. Remember the default patterns we set up for API routes – our Web API is available at a URL “http://localhost:<port>/api/Values”. So type the URL and hit enter. IE will show you the response as a JSON value. This is because IE always sends the Accept header as application.json and Web API server implementation will respect the content negotiation and send the appropriate data type to the client.

Fig 7: Testing API Controller in IE

Here is the same response when seen from Firefox:

Fig 8: Testing API Controller in Firefox


This was a post intended to show case the fact that Web API are not meant only for ASP.NET MVC project types but it can be hosted even in ASP.NET Web Forms project too. Thanks to the tooling, Visual Studio does all the magic under the hoods when you add a Item template of type “Web API Controller Class”. We saw how easy it is to set up a api controller and test it.  Hope this gives you a jump start on creating web API in web forms project. Do let me know if you have any feedback on this article. It will help me better myself.

Till next time – Happy Coding. Code with Passion, Decode with Patience.

  • Jonathan Taylor

    Hi. Great blog post. It works fine.

    I would like instances of my XxxController class to be created via IoC – say the constructor takes a repository interface as a parameter. Any ideas on how to do this ? In ASP.NET MVC, I believe there is a ControllerBuilder hook point but I guess this isn’t available in ASP.NET Web Forms.

    Jon Taylor

  • Sushant Kulkarni

    Do you have any idea about how to add api method in WebForm Code behind?

    • hi, unfortunately I don’t seem to get your question. can you please elaborate it ? If you are asking for “can we create a Web API Action Method” in code behind of web form – answer is no. It has its own processing pipe line and web form have their own processing pipe line. if you are asking about “can I consume a web api action in web form code behind” – absolutely. you can issue a HTTPClient call to the end point – get the JSON string from server and use JSON.NET to deserialize the string to object form.

      • Sushant Kulkarni

        Thanks Lohith, I got the answer.