.NET Zone is brought to you in partnership with:

My name is Lohith G N. I am a Production Engg by education but a Software Engg by profession. I have an industry experience of 10 years in software development. I started with Web Application Development with ASP.NET 1.1 in 2001. Now have expertise in Web Application Development using ASP.NET Web Forms & ASP.NET MVC, Windows Application Development using Win Forms & WPF, Service Oriented Development with WCF. I have been awarded Microsoft Most Valuable Person in Oct 2011 for ASP.NET/IIS area and focus on Open Data Protocol or OData. Lohith is a DZone MVB and is not an employee of DZone and has posted 22 posts at DZone. You can read more from them at their website. View Full User Profile

Web API in ASP.NET Web Forms Application

05.23.2013
| 13970 views |
  • submit to reddit

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:

image
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:

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

image
Fig 4: Adding Web API Controller Class

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

image 
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:

image
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)
{
    config.Routes.MapHttpRoute(
        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)
        {
            config.Routes.MapHttpRoute(
                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)
{
   WebApiConfig.Register(GlobalConfiguration.Configuration);
}

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.

image
Fig 7: Testing API Controller in IE

Here is the same response when seen from Firefox:

image
Fig 8: Testing API Controller in Firefox

Summary:

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.

Published at DZone with permission of Lohith Nagaraj, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)