Over a million developers have joined DZone.

Web API in ASP.NET Web Forms Application

DZone's Guide to

Web API in ASP.NET Web Forms Application

With the release of ASP.NET MVC 4 one of the exciting features packed in the release was ASP.NET Web API.

· Web Dev Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

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:

public static void Register(HttpConfiguration config)
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }

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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

namespace WebAPIinWebForms.App_Start
    public static class WebApiConfig
        public static void Register(HttpConfiguration config)
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

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:

protected void Application_Start(object sender, EventArgs e)

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.

Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

dotnet ,frameworks ,tools ,asp.net ,visual studio ,mvc

Published at DZone with permission of Lohith Nagaraj, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}