An introduction to WCF Web API

Pedro FĂ©lix, ISEL Tech 2011

Introduction

  • Extension to the Windows Communication Foundation
  • Announced at the 2010 PDC
    • Work in progress - currently in Preview 4
    • No final release date yet
  • Community participation
    • Feedback
    • However, no source code contribution

Goals

  • Development of web APIs, characterized by
    • Usage of HTTP as the application protocol (no SOAP)
    • Usage of multiple media types
    • Usage of multiple formats (e.g. XML, JSON)
    • Multiple architectural styles (e.g. RPC and ReST)
    • Consumption by multiple client devices
  • Base for ReST style system
    • Not "opinionated"
    • No resource model yet

Goals

  • Testability
    • E.g. No need for WebOperationContext.Current
    • E.g. Public constructors
  • Composability
    • IOC/DI friendly
  • Simpler configuration model
    • Code based

Availability

  • Source available at wcf.codeplex.com
    • hg clone https://hg01.codeplex.com/wcf
  • Nuget package
    • Install-Package WebApi.All

Programming Model

  • Original WCF programming model
    • Based on the SOAP and WSDL models
    • Transport independence
    • HTTP is a transport detail
  • Web API programming model
    • Based on the HTTP model
    • HTTP used as the application level protocol
    • Adds on the WCF original model

The Service Class

 1 [ServiceContract]
 2 class TheService
 3 {
 4     [WebGet(UriTemplate = "time")]
 5     HttpResponseMessage TheOperation(HttpRequestMessage req)
 6     {
 7         return new HttpResponseMessage()
 8         {
 9             StatusCode = HttpStatusCode.OK,
10             Content = new StringContent(
11                 DateTime.Now.ToLongTimeString())
12         };
13     }
14 }

Programming Model

  • ServiceContract is just a container for operations
  • Operations are instance methods annotated with
    • WebGet[UriTemplate="..."], or
    • WebInvoke[UriTemplate="...", Method="..."]
  • Operations handle HTTP requests selected by
    • The HTTP method (e.g. GET, POST)
    • The match between the Request URI and the URI template
  • Contract is a legacy term

HTTP messages

  • Strongly typed request and response messages
  • With public constructors

Operation Parameters

  • HttpRequestMessage
  • HttpRequestMessage<T>
  • URI template match bound variables
    • E.g. UriTemplate = "time/{zone}"
  • Query string pairs
  • A content model
  • Parameters injected by operation handlers

Operation return

  • HttpResponseMessage
  • HttpRespondeMessage<T>
  • A content model

The Service Host

 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         using (var host = new HttpServiceHost(typeof(TheService), 
 6             "http://localhost:8080"))
 7         {
 8             host.Open();
 9             Console.WriteLine("Host opened at {0} , press any key to end", 
10                 host.Description.Endpoints[0].Address);
11             Console.ReadKey();
12         }
13     }
14 }

Hosting

  • Similar to the original WCF model
    • service hosts and factories
  • Self-hosting
    • New HttpServiceHost
    • New HttpBinding
  • IIS hosting
    • RouteCollection extension methods

IIS Hosting

1 public class Global : System.Web.HttpApplication
2 {
3     protected void Application_Start(object sender, EventArgs e)
4     {
5         RouteTable.Routes.MapServiceRoute<TheService>("base_path");
6     }
7 }

Runtime Architecture

Runtime Architecture

  • Message Handlers
    • Receive a HttpRequestMessage
    • Must produce a HttpResponseMessage asynchronosly
    • Contains a reference to an inner channel
    • Endpoint scoped
  • Operation Handlers
    • Receive HttpParameter sets
    • Produce HttpParameter sets
    • Operation scoped

Message Handlers

Demo: message handler

Operation Handlers

  • Operation Handlers
    • Use parameters from a bag
    • Contribute with parameters to the same bag
  • Initially this bag contains
    • The HttpRequestMessage
    • The matched URITemplate bound variables
  • The final bag contents are usable by the operation

Demo: operation handler

Formatters

  • Operations can receive HttpRequestMessage<T> or a content model
  • Operations can return `HttpRequestMessage<T> or a content model
  • MediaTypeFormatter - conversion between the HTTP body and the content model
  • Supports server-driven content negotiation

Demo: media type formatters

Configuration

  • In prototyping phase
  • HttpHostConfiguration configuration builder
    • Fluent interface
  • HttpConfigurableServiceHost service host
  • RouteCollection extension methods receiving the configuration

Configuration

 1 var cfg = HttpHostConfiguration.Create()
 2     .AddMessageHandlers(typeof (SampleMessageHandler))
 3     .SetOperationHandlerFactory(new MyOperationConfigurationFactory());
 4 
 5 var host = new HttpConfigurableServiceHost(..., cfg, ...){
 6 
 7 class MyOperationConfigurationFactory : HttpOperationHandlerFactory{
 8     override Collection<HttpOperationHandler> 
 9     OnCreateRequestHandlers(
10         ServiceEndpoint endpoint, 
11         HttpOperationDescription operation){
12         var coll = base.OnCreateRequestHandlers(endpoint, operation);
13         coll.Add(new LoggingOperationHandler(operation));
14         if (operation.Name == "GetTimeString")
15         {
16             Formatters.Remove(Formatters.XmlFormatter);
17             Formatters.Remove(Formatters.JsonFormatter);
18             Formatters.Add(new WaveFromTextFormatter());
19             Formatters.Add(new ImageFromTextFormatter());
20         }
21         return coll;
22     }
23 }

Description

Resources

Q&A