Building RESTful Services with WCF 4.0

9,894 views

Published on

WCF provides first-class support for building "Web" services that embrace REST design principles using standard Web protocols and data formats. This session illustrates how to build WCF services that support the HTTP uniform interface and different resource representations like XML, JSON, and Atom to enhance your Web 2.0 mash-up solutions. Throughout the session we'll specifically look at some of the new features in WCF 4.0 and WCF Data Services.

Published in: Technology
1 Comment
8 Likes
Statistics
Notes
No Downloads
Views
Total views
9,894
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
0
Comments
1
Likes
8
Embeds 0
No embeds

No notes for slide

Building RESTful Services with WCF 4.0

  1. 1. Building RESTful Services with WCF Aaron Skonnard Cofounder, Pluralsight
  2. 2. Overview
  3. 3. Why REST?
  4. 4. Why REST?1. Most folks dont need SOAPs key features Transport-neutrality Advanced WS-* protocols Basic SOAP is just like REST but w/out the benefits
  5. 5. Why REST?2. REST is simple and the interface is uniform Its just HTTP + XML/JSON/XHTML Uniform interface that everyone understands Therefore, it’s more interoperable!
  6. 6. REST is not RPCSOAP 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. 7. Is REST too simple for complex systems?
  8. 8. Why REST?3. REST is how the Web works It scales from HTTPs built-in caching mechanisms Caching, bookmarking, navigating/links, SSL, etc You can access most REST services with a browser
  9. 9. REST in WCF
  10. 10. Windows Communication FoundationWCF doesnt take sides – it provides a unified programmingmodel 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. 11. WCF programming stylesMost of the built-in WCF bindings use SOAP & WS-* by default You have to configure them to disable SOAPWCF 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 templatesYou enable the Web model with a new binding/behavior Apply to messaging layer using WebHttpBinding Apply to dispatcher using WebHttpBehavior
  12. 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. 13. WebGetAttributeWebGetAttribute 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. 14. WebInvokeAttributeWebInvokeAttribute maps all other HTTP verbs to WCFmethods 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. 15. WebOperationContextUse WebOperationContext to access HTTP specifics withinmethods To retreived the current context use WebOperationContext.Current Provides properties for incoming/outgoing request/response contextEach context object surfaces most common HTTP details URI, ContentLength, ContentType, Headers, ETag, etc
  16. 16. WebMessageFormatWCF 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. 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 ... }
  18. 18. New in 4.0
  19. 19. Improved REST SupportMany features in the WCF REST Starter Kit are now part of WCF4.0
  20. 20. Automatic help pageWCF 4 provides an automatic help page for REST services Configure the <webHttp> behavior with helpEnabled=“true”
  21. 21. Message format selectionWCF 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. 22. Http caching supportWCF 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. 23. REST project templatesDownload the new REST project templates via the new VisualStudio 2010 Extension Manager (Tools | Extension Manager)
  24. 24. What about OData?
  25. 25. WCF Web Api Futureshttp://wcf.codeplex.com

×