Home > 2011 Fall DPS907, ASP.NET, Windows > Getting started with WCF Web API (on an ASP.NET web site)

Getting started with WCF Web API (on an ASP.NET web site)

September 23, 2011 Leave a comment Go to comments

This post will teach you how to get started with the new WCF Web API. We will use an ASP.NET web site to host the service.

.

This document was most recently updated in October 2011, and covers WCF Web API Preview 5.

It is the first post in a multipart series on WCF Web API, and is intended to be used by students in Seneca’s diploma- and degree-level software development programs, and any other entry- to mid-level developer.

.

What are we going to create?

We will create a RESTful web service, using the new WCF Web API.

WCF Web API is the successor to WCF WebHttp Services. For an introduction to the WCF Web API, read these documents:

WCF Web API – HTTP Your Way (Glenn Block, a Microsoft program manager)

WCF Web API Overview

Our service will include the following features:

  • We will write all code ourselves (in contrast to our WCF Data Services experience)
  • We will use new code libraries
  • It will publish a simple string “hello world” message
  • It will publish a collection of “employees”

.

The sections below will teach you how to create a WCF Web API service.

.

Reasons to choose WCF Web API

Recently, you gained some experience with WCF Data Services. You learned that WCF Data Services provides an easy and standardized way of exposing a data model over a RESTful interface, using the OData protocol. We covered entry-level material, learned its benefits, and acknowledged that more can be done by WCF Data Services.

As an alternative programming model, WCF Web API also provides access to resources and service operations over a RESTful interface.

The key differentiator between the two programming models is that WCF Web API provides the developer with complete control over the URI format and the service operations.

The following table captures some of the key characteristics of these two RESTful programming models:

.

WCF Web API WCF Data Services
Intended use RESTful web services RESTful web services
Key differentiator Developer has complete control over URI, and therefore the resources and service operations Easy and standardized way of exposing a data model over a RESTful interface
Depends upon New WCF classes that support HTTP services WCF, OData, and the OData runtime on the server
XML packaging Plain old XML (POX) (although other XML formats can be supported) Atom Syndication Format
JSON support Yes Yes
URI format Designed by the developer Specified by OData
Data access Entity Framework data model, with generated POCO (plain old CLR objects) classes Entity Framework data model
Data model exposure Determined by the developer Shaped by the Entity Framework data model (i.e. if the data model describes/includes the data, it’s available to the consumer), and entity set access rules
Release date Probably in late 2011 (we will work with Preview 5 this semester) August 2008 with .NET Framework 3.5 SP1

.

Comparing RESTful web service programming models with SOAP XML

At this point in time, it’s also useful to compare these RESTful web service programming models with the original SOAP XML web service programming model. (We’ll introduce SOAP XML web services near the end of the course.)

RESTful web services SOAP XML web services
Intended use RESTful web services SOAP XML web services
Key differentiator Resource-based approach to service operations, using the standard HTTP methods Single-endpoint (typically) approach, through which methods are published
Developer’s design… URI scheme, and the HTTP methods allowed on each URI template Method names, quantity, functionality, arguments, etc.
Depends upon WCF classes that support the RESTful programming model WCF classes that support SOAP XML
XML packaging Plain old XML (POX) (although other XML formats, like Atom Syndication Format, can be supported) SOAP XML
JSON support Yes No
URI format Designed by the developer (possibly assisted/enhanced by OData) Specified by the developer, typically as a single endpoint
Data access Entity Framework data model, maybe with generated POCO (plain old CLR objects) classes Entity Framework data model, adapted for SOAP XML
Data model exposure Determined by the developer, and shaped by the Entity Framework data model Determined by the developer, and shaped by the methods
Uses web infrastructure Yes, for GET (caching, etc.) Not as much (almost all requests are POSTS which cannot be cached)
Release date Around 2008 (and later) Around 1998

.

Let’s get started, and create a WCF Web API service.

.

Create an ASP.NET Empty Web Site

We need a “host” – an execution context and environment – for our web service.

An ASP.NET web site – specifically an “empty” web site – is ideal for an entry-level web services programmer. (Many currently-available code examples use an ASP.NET MVC web app as a host. ASP.NET MVC provides some infrastructure that performs certain content response tasks auto-magically. For this “getting started” note and series, we decided that you should build all the code yourself. It’s not all that difficult.)

In Visual Studio 2010, File > New > Web Site…, and use the following settings:

  • Visual C#
  • ASP.NET Empty Web Site
  • Web location: File System (and specify a new folder, maybe called “webapi”)

.

.

Here’s what we will do in the following sections:

  • Add the new WCF Web API code libraries to the web site
  • Configure a “specific page” to show when you start/run the web site
  • Add a class that holds our executable code
  • Configure “ASP.NET Routing” to enable URI handling
  • Add a method that will display a collection

.

Add the WCF Web API code libraries

In Solution Explorer, right-click on the web site project name, and choose Manage NuGet Packages.

NuGet is a “package manager”. NuGet simplifies the task of adding code libraries to a project. We need to use NuGet, because the functionality we need is not yet included in the .NET Framework 4 release.

If “Manage NuGet Packages” does not appear on the context menu…

On your computer, you can install NuGet. On the College computers, you will have to install NuGet after the computer powers on.

In Visual Studio 2010, on the Tools menu, choose Extension Manager. On the left side, select Online Gallery, and in the upper-right search field, search for “nuget”. Choose the “NuGet Package Manager”, and download and install it.

.

On the left side, select Online, and in the upper-right search field, search for “webapi”. Choose the WebApi.All package, and Install it.

.

Configure a “specific page” to show when you start/run the web site

In Solution Explorer, right-click on the web site project name, and choose Start Options. Choose Specific Page, and enter a page name.

This is a virtual page, which doesn’t actually exist, but it will be the base page in your web service URI. In the example below, the page name is “svc”, which means that the web service URI will be:

http://host.domain.com/svc/

.

Add a class that holds your executable code

Next, add a class that holds your executable code. Its name will be “Service.cs”. (When you “Add New Item”, you are prompted to place it in the ‘App_Code’ folder, because the folder doesn’t yet exist. As a reminder, yes, you want to do this.)

Add new directives, and replace the class declaration, with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
// Web service namespaces
using System.ServiceModel;
using System.ServiceModel.Web;
// Additional namespaces
using System.Net;
using System.Net.Http;
using Microsoft.ApplicationServer.Http.Dispatcher;

[ServiceContract]
public class Operations
{
    // Remove this method from an in-production (deployed) web service
    [WebGet(UriTemplate = "")]
    public string ServiceRoot()
    {
        return "Append /test to the URI to use the HTTP Test Client";
    }
}

.

Here’s what this code is doing:

  • The [ServiceContract] attribute enables the class’ methods to be web-accessible
  • It has one method, ServiceRoot(), which will return a simple string
  • The method will respond to the HTTP GET method request

.

Configure “ASP.NET Routing” to enable URI handling

You know from your ASP.NET Web Forms programming experience that a browser user must request a resource that actually exists (e.g. default.aspx). You also know that a browser user is not able to request a resource that is located in the App_Code folder. In addition, the ASP.NET runtime (on the server) will not deliver a C# code file resource (e.g. “whatever.cs”).

How do we make our new service and its methods available? By using ASP.NET Routing.

Here’s an introduction to ASP.NET Routing.

Here’s a “how to” document.

Follow this procedure to configure ASP.NET routing for a WCF Web API web site.

Add a Global.asax to your web site.

After the Application directive, add the following Import directives:

<%@ Import Namespace="System.ServiceModel.Activation" %>
<%@ Import Namespace="Microsoft.ApplicationServer.Http.Activation" %>
<%@ Import Namespace="System.Web.Routing" %>

Add the following new method in the script code area:

public static void RegisterRoutes(RouteCollection routes)
{
    // Enable the HTTP Test Client (during development and testing only)
    var config = new Microsoft.ApplicationServer.Http.HttpConfiguration() { EnableTestClient = true };
    // Add it to the new service route
    routes.Add(new ServiceRoute("svc", new HttpServiceHostFactory() { Configuration = config }, typeof(Operations)));

    // Remove (or comment out) the above statements in an in-production (deployed)
    // web service, and un-comment the following statement
    //routes.Add(new ServiceRoute("svc", new HttpServiceHostFactory(), typeof(Operations)));
}

.

In the Application_Start method, call the method:

RegisterRoutes(RouteTable.Routes);

.

Your web service is now ready – run it

On the Debug menu, choose Start Without Debugging. It should appear as follows:

.

Activate the WCF Web API “HTTP Test Client”

WCF Web API includes an HTTP Test Client. Its function is similar to your Lab 1 work.

The HTTP Test Client code was already added to the RegisterRoutes method in Global.asax. Therefore, it’s ready to use.

To use the HTTP Test Client, add “test” to the URI. For example:

http://host.domain.com/svc/test

.

Checkpoint… save your project as a “template”

The work you have just completed should be saved as a “template”. When you create new WCF Web API services in the future, all will have the features you just coded.

Therefore, exit Visual Studio, locate the folder that contains your work, and copy it.

In the future, you can copy-paste the folder, and File > Open > Web Site in Visual Studio.

.

Add a method and URI template to display a collection

Next, we will add a model class for an employee. Then, we will add a method, and a URI template, to initialize and display a collection of employee objects.

The collection will be created in-memory, and will not be persisted.

.

Add a model class for an “employee”

Add a new class to the App_Code folder. Call it Employee.cs. It will be a simple class, as shown below.

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

public class Employee
{
    public int EmployeeID { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

.

Add a method and URI template

We know that our ServiceRoot() method returns a simple string. We can display the string by requesting the web service’s base URI.

Now, we want to add the ability to request a collection of employee objects. We will need a URI template, and a method that will service that URI template.

As noted above, the collection will be created in the method body. We will not persist the collection – it will be a temporary collection.

Let’s assume that the URI template will be “employees”. That is, we will append “employees” to the web service’s base URI. For example:

http://host.domain.com/svc/employees

We add a URI template and a method in the service class. Add the following method to the public class Employees. Notice the syntax of the WebGet attribute.

    [WebGet(UriTemplate="employees")]
    public IEnumerable<Employee> AllEmployees()
    {
        var employees = new List<Employee>()
        {
            new Employee{EmployeeID=1, FirstName="Peter", LastName="McIntyre"},
            new Employee{EmployeeID=2, FirstName="Ian", LastName="Tipson"}
        };
        return employees;
    }

.

Display the results

On the Debug menu, choose Start Without Debugging. Add “/employees” to the URI. It should appear as follows:

.

What’s next

In later posts, we will:

  • work with a persistent store, through an Entity Framework data model
  • support POST, PUT, and DELETE HTTP methods
  • add security to the web service

.


.

.

.

Advertisement
  1. No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.