SlideShare a Scribd company logo
Building RESTful Services with
                         WCF
                        Aaron Skonnard
                   Cofounder, Pluralsight
Overview
Why REST?
Why REST?

1. Most folks don't need SOAP's key features
     Transport-neutrality
     Advanced WS-* protocols
     Basic SOAP is just like REST but w/out the benefits
Why REST?

2. REST is simple and the interface is uniform
     It's just HTTP + XML/JSON/XHTML
     Uniform interface that everyone understands
     Therefore, it’s more interoperable!
REST is not RPC

SOAP emphasizes verbs while REST emphasizes nouns or
"resources"
SOAP                        REST                          With REST, you define
                                                                resources,
 getUser()                                             and use a uniform interface to
 addUser()                   User { }                  operate on them (HTTP verbs)
 removeUser()                Location { }
 ...
 getLocation()                                             XML representation
 addLocation()
 ...                         <user>
                               <name>Jane User</name>
 With SOAP, you define         <gender>female</gender>
custom operations (new         <location href="http://example.org/locations/us/ny/nyc"
                               >New York City, NY, US</location>
verbs), tunnels through
                             </user>
          POST
Is REST too simple for complex systems?
Why REST?

3. REST is how the Web works
     It scales from HTTP's built-in caching mechanisms
     Caching, bookmarking, navigating/links, SSL, etc
     You can access most REST services with a browser
REST in WCF
Windows Communication Foundation

WCF doesn't take sides – it provides a unified programming
model
   And allows you to use SOAP, POX, REST, whatever data format, etc


           Architecture: SOAP, REST, distributed objects, etc

               Transport Protocol: HTTP, TCP, MSMQ, etc
 WCF
             Message format: XML, RSS, JSON, binary, etc

                   Message protocols: WS-*, none, etc
WCF programming styles

Most of the built-in WCF bindings use SOAP & WS-* by default
   You have to configure them to disable SOAP
WCF 3.5 comes with a new Web (REST) programming model
   Found in System.ServiceModel.Web.dll
   Allows you to map HTTP requests to methods via URI templates
You enable the Web model with a new binding/behavior
   Apply to messaging layer using WebHttpBinding
   Apply to dispatcher using WebHttpBehavior
WebServiceHost

     WebServiceHost simplifes hosting Web-based services
        Derives from ServiceHost and overrides OnOpening
        Automatically adds endpoint for the base address using
        WebHttpBinding
        Automatically adds WebHttpBehavior to the endpoint

               ...
 this host     WebServiceHost host = new WebServiceHost(
 adds the          typeof(EvalService),
Web binding        new Uri("http://localhost:8080/evals"));
& behavior     host.Open(); // service is up and running
               Console.ReadLine(); // hold process open
               ...

     <%@ ServiceHost Language="C#" Service="EvalService" Factory=
         "System.ServiceModel.Activation.WebScriptServiceFactory" %>
WebGetAttribute

WebGetAttribute maps HTTP GET requests to a WCF method
   Supply a UriTemplate to defining URI mapping
   The UriTemplate variables map to method parameters by name
   BodyStyle property controls bare vs. wrapped
   Request/ResponseFormat control body format
                                               URI template

[ServiceContract]
public interface IEvalService
{
    [WebGet(UriTemplate="evals?name={name}&score={score}")]
    [OperationContract]
    List<Eval> GetEvals(string name, int score);
...
WebInvokeAttribute

WebInvokeAttribute maps all other HTTP verbs to WCF
methods
   Adds a Method property for specifying the verb (default is POST)
   Allows mapping UriTemplate variables
                                                 Specify which
   Body is deserialized into remaining parameter HTTP verb this
                                                  responds to

 [ServiceContract]
 public interface IEvals
 {
     [WebInvoke(UriTemplate ="/evals?name={name}",Method="PUT")]
     [OperationContract]
     void SubmitEval(string name, Eval eval /* body */);
 ...
WebOperationContext

Use WebOperationContext to access HTTP specifics within
methods
   To retreived the current context use WebOperationContext.Current
   Provides properties for incoming/outgoing request/response context
Each context object surfaces most common HTTP details
   URI, ContentLength, ContentType, Headers, ETag, etc
WebMessageFormat

WCF provides support for two primary Web formats: XML &
JSON
   You control the format via RequestFormat and ResponseFormat

  [ServiceContract]
  public interface IEvals
  {
      [WebGet(UriTemplate = "/evals?name={nameFilter}",
          ResponseFormat = WebMessageFormat.Json)]
      [OperationContract]
      List<Eval> GetCurrentEvals(string nameFilter);
  ...

                               Specify the message format
Syndication programming model

    WCF comes with a simplified syndication programming model
       The logical data model for a feed is SyndicationFeed
       You can use it to produce/consume feeds in a variety of formats
    You use a SyndicationFeedFormatter to work with a specific
    format
       Use Atom10FeedFormatter or RSS20FeedFormatter today
                       [ServiceKnownType(typeof(Atom10FeedFormatter))]
                       [ServiceKnownType(typeof(Rss20FeedFormatter))]
                       [ServiceContract]
                       public interface IEvalService {
                           [WebGet(UriTemplate = "evalsfeed")]
                           [OperationContract]
allows you to return
                           SyndicationFeedFormatter GetEvalsFeed();
an Atom or RSS feed    ...
                       }
New in 4.0
Improved REST Support

Many features in the WCF REST Starter Kit are now part of WCF
4.0
Automatic help page

WCF 4 provides an automatic help page for REST services
   Configure the <webHttp> behavior with helpEnabled=“true”
Message format selection

WCF 4 also provides automatic format selection for XML/JSON
   This feature is built on the HTTP “Accept” headers



<configuration>
  <system.serviceModel>
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="true"
            automaticFormatSelectionEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>
</configuration>
Http caching support

WCF 4 provides a simpler model for managing HTTP caching
   They built on the ASP.NET caching profile architecture
   You define an [AspNetCacheProfile] for your GET operations
   Shields you from dealing with HTTP caching headers yourself



     [AspNetCacheProfile("CacheFor60Seconds")]
     [WebGet(UriTemplate=XmlItemTemplate)]
     [OperationContract]
     public Counter GetItemInXml()
     {
         return HandleGet();
     }
REST project templates

Download the new REST project templates via the new Visual
Studio 2010 Extension Manager (Tools | Extension Manager)
What about
 OData?
WCF Web Api
  Futures
http://wcf.codeplex.com

More Related Content

PDF
Windows Communication Foundation (WCF)
PPTX
10 Tricks and Tips for WCF
PPTX
WCF Fundamentals
PPT
Wcf architecture overview
PDF
REST, JSON and RSS with WCF 3.5
PPT
Interoperability and Windows Communication Foundation (WCF) Overview
PDF
Wcf development
DOC
WCF tutorial
Windows Communication Foundation (WCF)
10 Tricks and Tips for WCF
WCF Fundamentals
Wcf architecture overview
REST, JSON and RSS with WCF 3.5
Interoperability and Windows Communication Foundation (WCF) Overview
Wcf development
WCF tutorial

What's hot (20)

PPTX
Windows Communication Foundation (WCF) Best Practices
PPTX
Windows Communication Foundation (WCF)
PPT
WCF And ASMX Web Services
PPTX
WCF (Windows Communication Foundation)
PPTX
WCF for begineers
PPT
introduction to Windows Comunication Foundation
PPT
PPTX
Introduction to WCF
PPTX
Windows Communication Foundation (WCF) Service
PPTX
WCF Introduction
PPT
PPTX
1. WCF Services - Exam 70-487
PPTX
Enjoying the Move from WCF to the Web API
PPT
Session 1: The SOAP Story
PPTX
Web API or WCF - An Architectural Comparison
PPT
Web services, WCF services and Multi Threading with Windows Forms
PDF
Web Services (SOAP, WSDL, UDDI)
PPTX
Advancio, Inc. Academy: Web Sevices, WCF & SOAPUI
PPT
Intro to web services
Windows Communication Foundation (WCF) Best Practices
Windows Communication Foundation (WCF)
WCF And ASMX Web Services
WCF (Windows Communication Foundation)
WCF for begineers
introduction to Windows Comunication Foundation
Introduction to WCF
Windows Communication Foundation (WCF) Service
WCF Introduction
1. WCF Services - Exam 70-487
Enjoying the Move from WCF to the Web API
Session 1: The SOAP Story
Web API or WCF - An Architectural Comparison
Web services, WCF services and Multi Threading with Windows Forms
Web Services (SOAP, WSDL, UDDI)
Advancio, Inc. Academy: Web Sevices, WCF & SOAPUI
Intro to web services
Ad

Similar to Building RESTful Services with WCF 4.0 (20)

PPT
Building+restful+webservice
PPT
Developing RESTful WebServices using Jersey
PPTX
Jax ws
 
PDF
Webservices in SalesForce (part 1)
PPTX
RESTful WCF Services
PPT
Java Servlets
PDF
SharePoint Alerts with WCF and jQuery
PPTX
Java servlets
PPTX
Servlets
PPTX
JAX-RS 2.0 and OData
PPTX
Http Server Programming in JAVA - Handling http requests and responses
PDF
Wcf remaining
DOCX
Android ax app wcf
PPTX
PPTX
Android+ax+app+wcf
PPTX
Automated testing web services - part 1
PPTX
CodeMash 2013 Microsoft Data Stack
PPT
Rest Service In Mule
PDF
JavaEE6 my way
PPT
Jsp/Servlet
Building+restful+webservice
Developing RESTful WebServices using Jersey
Jax ws
 
Webservices in SalesForce (part 1)
RESTful WCF Services
Java Servlets
SharePoint Alerts with WCF and jQuery
Java servlets
Servlets
JAX-RS 2.0 and OData
Http Server Programming in JAVA - Handling http requests and responses
Wcf remaining
Android ax app wcf
Android+ax+app+wcf
Automated testing web services - part 1
CodeMash 2013 Microsoft Data Stack
Rest Service In Mule
JavaEE6 my way
Jsp/Servlet
Ad

More from Saltmarch Media (18)

PDF
Concocting an MVC, Data Services and Entity Framework solution for Azure
PDF
Caring about Code Quality
PDF
Learning Open Source Business Intelligence
PDF
Java EE 7: the Voyage of the Cloud Treader
PDF
Is NoSQL The Future of Data Storage?
PDF
Introduction to WCF RIA Services for Silverlight 4 Developers
PDF
Integrated Services for Web Applications
PDF
Gaelyk - Web Apps In Practically No Time
PDF
CDI and Seam 3: an Exciting New Landscape for Java EE Development
PDF
JBoss at Work: Using JBoss AS 6
PDF
WF and WCF with AppFabric – Application Infrastructure for OnPremise Services
PDF
“What did I do?” - T-SQL Worst Practices
PDF
Building Facebook Applications on Windows Azure
PDF
Architecting Smarter Apps with Entity Framework
PDF
Agile Estimation
PDF
Alternate JVM Languages
PDF
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
PDF
A Bit of Design Thinking for Developers
Concocting an MVC, Data Services and Entity Framework solution for Azure
Caring about Code Quality
Learning Open Source Business Intelligence
Java EE 7: the Voyage of the Cloud Treader
Is NoSQL The Future of Data Storage?
Introduction to WCF RIA Services for Silverlight 4 Developers
Integrated Services for Web Applications
Gaelyk - Web Apps In Practically No Time
CDI and Seam 3: an Exciting New Landscape for Java EE Development
JBoss at Work: Using JBoss AS 6
WF and WCF with AppFabric – Application Infrastructure for OnPremise Services
“What did I do?” - T-SQL Worst Practices
Building Facebook Applications on Windows Azure
Architecting Smarter Apps with Entity Framework
Agile Estimation
Alternate JVM Languages
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
A Bit of Design Thinking for Developers

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Empathic Computing: Creating Shared Understanding
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Encapsulation theory and applications.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
KodekX | Application Modernization Development
NewMind AI Weekly Chronicles - August'25 Week I
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
MIND Revenue Release Quarter 2 2025 Press Release
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Unlocking AI with Model Context Protocol (MCP)
Mobile App Security Testing_ A Comprehensive Guide.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
The Rise and Fall of 3GPP – Time for a Sabbatical?
Empathic Computing: Creating Shared Understanding
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Encapsulation theory and applications.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Encapsulation_ Review paper, used for researhc scholars
KodekX | Application Modernization Development

Building RESTful Services with WCF 4.0

  • 1. Building RESTful Services with WCF Aaron Skonnard Cofounder, Pluralsight
  • 4. Why REST? 1. Most folks don't need SOAP's key features Transport-neutrality Advanced WS-* protocols Basic SOAP is just like REST but w/out the benefits
  • 5. Why REST? 2. REST is simple and the interface is uniform It's just HTTP + XML/JSON/XHTML Uniform interface that everyone understands Therefore, it’s more interoperable!
  • 6. REST is not RPC SOAP emphasizes verbs while REST emphasizes nouns or "resources" SOAP REST With REST, you define resources, getUser() and use a uniform interface to addUser() User { } operate on them (HTTP verbs) removeUser() Location { } ... getLocation() XML representation addLocation() ... <user> <name>Jane User</name> With SOAP, you define <gender>female</gender> custom operations (new <location href="http://example.org/locations/us/ny/nyc" >New York City, NY, US</location> verbs), tunnels through </user> POST
  • 7. Is REST too simple for complex systems?
  • 8. Why REST? 3. REST is how the Web works It scales from HTTP's built-in caching mechanisms Caching, bookmarking, navigating/links, SSL, etc You can access most REST services with a browser
  • 10. Windows Communication Foundation WCF doesn't take sides – it provides a unified programming model And allows you to use SOAP, POX, REST, whatever data format, etc Architecture: SOAP, REST, distributed objects, etc Transport Protocol: HTTP, TCP, MSMQ, etc WCF Message format: XML, RSS, JSON, binary, etc Message protocols: WS-*, none, etc
  • 11. WCF programming styles Most of the built-in WCF bindings use SOAP & WS-* by default You have to configure them to disable SOAP WCF 3.5 comes with a new Web (REST) programming model Found in System.ServiceModel.Web.dll Allows you to map HTTP requests to methods via URI templates You enable the Web model with a new binding/behavior Apply to messaging layer using WebHttpBinding Apply to dispatcher using WebHttpBehavior
  • 12. WebServiceHost WebServiceHost simplifes hosting Web-based services Derives from ServiceHost and overrides OnOpening Automatically adds endpoint for the base address using WebHttpBinding Automatically adds WebHttpBehavior to the endpoint ... this host WebServiceHost host = new WebServiceHost( adds the typeof(EvalService), Web binding new Uri("http://localhost:8080/evals")); & behavior host.Open(); // service is up and running Console.ReadLine(); // hold process open ... <%@ ServiceHost Language="C#" Service="EvalService" Factory= "System.ServiceModel.Activation.WebScriptServiceFactory" %>
  • 13. WebGetAttribute WebGetAttribute maps HTTP GET requests to a WCF method Supply a UriTemplate to defining URI mapping The UriTemplate variables map to method parameters by name BodyStyle property controls bare vs. wrapped Request/ResponseFormat control body format URI template [ServiceContract] public interface IEvalService { [WebGet(UriTemplate="evals?name={name}&score={score}")] [OperationContract] List<Eval> GetEvals(string name, int score); ...
  • 14. WebInvokeAttribute WebInvokeAttribute maps all other HTTP verbs to WCF methods Adds a Method property for specifying the verb (default is POST) Allows mapping UriTemplate variables Specify which Body is deserialized into remaining parameter HTTP verb this responds to [ServiceContract] public interface IEvals { [WebInvoke(UriTemplate ="/evals?name={name}",Method="PUT")] [OperationContract] void SubmitEval(string name, Eval eval /* body */); ...
  • 15. WebOperationContext Use WebOperationContext to access HTTP specifics within methods To retreived the current context use WebOperationContext.Current Provides properties for incoming/outgoing request/response context Each context object surfaces most common HTTP details URI, ContentLength, ContentType, Headers, ETag, etc
  • 16. WebMessageFormat WCF provides support for two primary Web formats: XML & JSON You control the format via RequestFormat and ResponseFormat [ServiceContract] public interface IEvals { [WebGet(UriTemplate = "/evals?name={nameFilter}", ResponseFormat = WebMessageFormat.Json)] [OperationContract] List<Eval> GetCurrentEvals(string nameFilter); ... Specify the message format
  • 17. Syndication programming model WCF comes with a simplified syndication programming model The logical data model for a feed is SyndicationFeed You can use it to produce/consume feeds in a variety of formats You use a SyndicationFeedFormatter to work with a specific format Use Atom10FeedFormatter or RSS20FeedFormatter today [ServiceKnownType(typeof(Atom10FeedFormatter))] [ServiceKnownType(typeof(Rss20FeedFormatter))] [ServiceContract] public interface IEvalService { [WebGet(UriTemplate = "evalsfeed")] [OperationContract] allows you to return SyndicationFeedFormatter GetEvalsFeed(); an Atom or RSS feed ... }
  • 19. Improved REST Support Many features in the WCF REST Starter Kit are now part of WCF 4.0
  • 20. Automatic help page WCF 4 provides an automatic help page for REST services Configure the <webHttp> behavior with helpEnabled=“true”
  • 21. Message format selection WCF 4 also provides automatic format selection for XML/JSON This feature is built on the HTTP “Accept” headers <configuration> <system.serviceModel> <standardEndpoints> <webHttpEndpoint> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/> </webHttpEndpoint> </standardEndpoints> </system.serviceModel> </configuration>
  • 22. Http caching support WCF 4 provides a simpler model for managing HTTP caching They built on the ASP.NET caching profile architecture You define an [AspNetCacheProfile] for your GET operations Shields you from dealing with HTTP caching headers yourself [AspNetCacheProfile("CacheFor60Seconds")] [WebGet(UriTemplate=XmlItemTemplate)] [OperationContract] public Counter GetItemInXml() { return HandleGet(); }
  • 23. REST project templates Download the new REST project templates via the new Visual Studio 2010 Extension Manager (Tools | Extension Manager)
  • 25. WCF Web Api Futures http://wcf.codeplex.com