New Features of WCF 4.0: Part IV

Previous Articles

Introduction

 
Microsoft.NET 4.0 and Visual Studio.NET 2010 ships a lot of new features in their underlying technologies. In this series of articles, I want to talk about the new features in the area of Windows Communication Foundation (WCF) in order to improve the development experience, enable more communication scenario, support new WS-* standards and provide a good integration with Windows Workflow Foundation (WF).
 
The new features are essentially the following: simplified configuration, standard endpoints, IIS hosting without a SVC file, support for WS-Discovery, routing service, REST improvements, enhancements for the integration with WF to support workflow services, simple byte stream encoding and ETW tracing.
 
In this series of article, I will illustrate each feature explaining the principles and showing some examples.
 

REST improvements in WCF 4.0

 
WCF ships a lot of improvements for the development of Web services using REST approach. These features can be accessed using the WebHttpBinding binding. Many of these features were introduced in the WCF Rest Starter Kit and now they are part of Microsoft.NET framework.
 
Automatic help page. This is a nice feature because REST Web services have a lack of description mechanisms to provide the metadata associated with the service. When you host a service using WebServiceHost in WCF 4, a help page is generated automatically. This is done using the WebHttpBinding and WebHttpBehavior configuration by default in an environment defined by a WebServiceHost instance. The WebHttpBehavior comes with a HelpEnabled property to enable or disable the help page feature.
 
Let's apply this principle to the EchoService developed in previous articles. Let's create a console application to host our REST service.
 
Now let's add the references to the WCF libraries needed to build the solution. We need to add the System.ServiceModel.dll and System.ServiceModel.Web.dll assemblies (see Figure 1).
 
WCF1.gif 
Figure 1
 
If you don't see the System.ServiceModel.Web.dll assembly from the Add Reference dialog box, you have to right-click on the console application project and select the Properties option from the context menu. When the Properties page appears, from the Application tab go to the Target frameworks field and change to the .NET Framework 4 option (see Figure 2).
WCF2.gif 
Figure 2
 
Next step is to define the service contract. We're going to use the WCF artifacts and extensions to REST Web services. In this case, we're going to call the EchoService using traditional HTTP Get and HTTP Post methods (two operations for each HTTP method) and the messages will be encapsulated using plain old HTTP ways (see the Listing 1).

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.Text;  
  6. using System.ServiceModel;  
  7. using System.ServiceModel.Web;  
  8. namespace WCF_NewFeatures  
  9. {  
  10.     [ServiceContract]  
  11.     public interface IEchoService  
  12.     {  
  13.         [OperationContract]  
  14.         [WebGet]  
  15.         string EchoGetMethod(String message);  
  16.   
  17.         [OperationContract]  
  18.         [WebInvoke]  
  19.         string EchoPostMethod(String message);  
  20.     }  
  21. }
Listing 1
 
Next step is to realize the contract with a concrete service (see the Listing 2). In this case, the outgoing messages of the service will be in plain format, although we can use different format for the message such as XML, Json, etc. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7.   
  8. namespace WCF_NewFeatures  
  9. {  
  10.     public class EchoService : IEchoService  
  11.     {  
  12.         #region IEchoService Members  
  13.         public string EchoGetMethod(string message)  
  14.         {  
  15.             return "EchoGetMethod invoked using HTTP Get method. Message is " + message;  
  16.         }  
  17.   
  18.         public string EchoPostMethod(string message)  
  19.         {  
  20.             return "EchoGetMethod invoked using HTTP Post method. Message is " + message;  
  21.         }  
  22.         #endregion  
  23.     }  
  24. } 
Listing 2
 
Next step is to define the WCF artifacts in order to host the service in the console application (see Listing 3).
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Description;  
  7. using System.ServiceModel.Web;  
  8.   
  9. namespace WCF_NewFeatures  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             WebServiceHost serviceHost = new WebServiceHost(typeof(WCF_NewFeatures.EchoService),new Uri("http://localhost:8080/Services/EchoService"));  
  16.             serviceHost.Open();  
  17.   
  18.             System.Console.WriteLine("The EchoService has started");  
  19.             foreach (ServiceEndpoint se in serviceHost.Description.Endpoints)  
  20.             {  
  21.                 System.Console.WriteLine("Address:{0}, Binding:{1}, Contract:{2}", se.Address, se.Binding.Name, se.Contract.Name);  
  22.             }  
  23.             System.Console.WriteLine("Please, press any key to finish ...");  
  24.             System.Console.ReadLine();  
  25.   
  26.             serviceHost.Close();  
  27.         }  
  28.     }  
  29. } 
Listing 3
 
When you configure a WebServiceHost instance to host a service, it automatically configures your service with the WebHttpBehavior and adds a default HTTP endpoint configured with the WebHttpBinding at the base address. The only thing to do is to set the HelpEnabled property to true of the WebHttpBehavior (see Listing 4).
  1. <?xml version="1.0"?>  
  2. <configuration>  
  3.        <system.serviceModel>  
  4.               <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />  
  5.               <services>  
  6.                      <service name="WCF_NewFeatures.EchoService">  
  7.                            <endpoint address="" behaviorConfiguration="WCF_NewFeatures.EchoServiceBehavior" binding="webHttpBinding" contract="WCF_NewFeatures.IEchoService">  
  8.                            </endpoint>  
  9.                      </service>  
  10.               </services>  
  11.               <behaviors>  
  12.                      <endpointBehaviors>  
  13.                            <behavior name="WCF_NewFeatures.EchoServiceBehavior">  
  14.                                   <webHttp helpEnabled="true" />  
  15.                            </behavior>  
  16.                      </endpointBehaviors>  
  17.               </behaviors>  
  18.        </system.serviceModel>  
  19. <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>  
Listing 4
 
Now you can see the help page by browsing to the service's base address and appending the help string to the end of the url (see Listing 4).
 
WCF3.gif 
Figure 3
 
If you see the help page, you realize that you can test the EchoGetMethod operation of the service by sending a request using HTTP GET method and passing information in the message parameter. This can be easily done using the browser and the following url http://localhost:8080/Services/EchoService/EchoGetMethod?message=test and see the result in Figure 4.
 
WCF4.gif 
Figure 4 
 
Let's see how you can configure the Help Page feature using code without the need of the configuration file (see Listing 5). 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Description;  
  7. using System.ServiceModel.Web;  
  8.   
  9. namespace WCF_NewFeatures  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             WebServiceHost serviceHost = new WebServiceHost(typeof(WCF_NewFeatures.EchoService),new Uri("http://localhost:8080/Services/EchoService"));  
  16.             serviceHost.AddServiceEndpoint(typeof(WCF_NewFeatures.IEchoService), new WebHttpBinding(),"");  
  17.             serviceHost.Description.Endpoints[0].Behaviors.Add(new WebHttpBehavior { HelpEnabled = true});  
  18.             serviceHost.Open();  
  19.   
  20.             System.Console.WriteLine("The EchoService has started");  
  21.             foreach (ServiceEndpoint se in serviceHost.Description.Endpoints)  
  22.             {  
  23.                 System.Console.WriteLine("Address:{0}, Binding:{1}, Contract:{2}", se.Address, se.Binding.Name, se.Contract.Name);  
  24.             }  
  25.             System.Console.WriteLine("Please, press any key to finish ...");  
  26.             System.Console.ReadLine();  
  27.   
  28.             serviceHost.Close();  
  29.         }  
  30.     }  
  31. } 
Listing 5
 
You can control the REST binding such as message formats and uri template (to apply to REST uri style) using the properties of the WebGet and WebInvoke attribute (see Table 1). 
 
Property Name Type Possible Value Description
BodyStyle WebMessageBodyStyle Bare
Wrapped
WrappedRequest
WrappedResponse
Controls the aspects of the message envelop.
RequestFormat WebMessageFormat Json
XML
Specifies the message format for the request
ResponseFormat WebMessageFormat Json
XML
Specifies the message format for the response
UriTemplate String Any string
representing a valid
uri
The template that matches against the incoming request
Table 1
 
Let me demonstrate how to describe the shape of the URIs to which the EchoService will respond. For example, let's change the request URI for the service by adding the following pattern GetEcho/{message} for the GET method, and PostEcho/{message} for the POST method where the message is the parameter. Now you can access to the service and pass the parameters in this way, http://localhost:8080/Services/EchoService/getecho/mymessage (see Figure 5).
 
WCF5.gif 
Figure 5
 
Let me demonstrate how to support different message format, for example, XML and Json. Now, we're going to change the interface to expose two operations for processing messages coming using HTTP Get method and sending the response either by XML or Json depending on the request URI as shown in the previous example (see Listing 6).

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.Text;  
  6. using System.ServiceModel;  
  7. using System.ServiceModel.Web;  
  8.   
  9. namespace WCF_NewFeatures  
  10. {  
  11.     [ServiceContract]  
  12.     public interface IEchoService  
  13.     {  
  14.         [OperationContract]  
  15.         [WebGet(UriTemplate="GetEcho/json/{message}", ResponseFormat=WebMessageFormat.Json)]  
  16.         string EchoGetMethodJson(String message);  
  17.   
  18.         [OperationContract]  
  19.         [WebGet(UriTemplate = "GetEcho/xml/{message}", ResponseFormat = WebMessageFormat.Xml)]  
  20.         string EchoGetMethodXml(String message);  
  21.   
  22.         [OperationContract]  
  23.         [WebInvoke(UriTemplate = "PostEcho/{message}")]  
  24.         string EchoPostMethod(String message);  
  25.     }  
  26. }
Listing 6
 
And the implementation of the contract is shown in the service of the Listing 7. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.Text;  
  7.   
  8. namespace WCF_NewFeatures  
  9. {  
  10.     public class EchoService : IEchoService  
  11.     {  
  12.         #region IEchoService Members  
  13.         public string EchoGetMethodJson(string message)  
  14.         {  
  15.             return "EchoGetMethodJson invoked using HTTP Get method. Message is (Json format) " + message;  
  16.         }  
  17.   
  18.         public string EchoGetMethodXml(string message)  
  19.         {  
  20.             return "EchoGetMethodXml invoked using HTTP Get method. Message is (Xml format) " + message;  
  21.         }  
  22.    
  23.         public string EchoPostMethod(string message)  
  24.         {  
  25.             return "EchoGetMethod invoked using HTTP Post method. Message is " + message;  
  26.         }  
  27.         #endregion  
  28.     }  
  29. }
Listing 7
 
Going to the Help Page for the service, you will find the description of the service and the way to access to this (see Figure 6).
 
WCF6.gif 
Figure 6
 
So, you can access to the service using the HTTP Get method and receiving the response formatted using Json by the following URI http://localhost:8080/Services/EchoService/getecho/json/mymessage.
 
In WCF 4.0 you can also access to the request and message format at runtime. Let's create a generic getecho operation passing as parameter the format of the outgoing message and processing this information at runtime.
 
Let's redefine the service contract again as shown in Listing 8. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.Text;  
  6. using System.ServiceModel;  
  7. using System.ServiceModel.Web;  
  8.   
  9. namespace WCF_NewFeatures  
  10. {  
  11.     [ServiceContract]  
  12.     public interface IEchoService  
  13.     {  
  14.         [OperationContract]  
  15.         [WebGet(UriTemplate="GetEcho/{message}")]  
  16.         string EchoGetMethod(String message);  
  17.   
  18.         [OperationContract]  
  19.         [WebInvoke(UriTemplate = "PostEcho/{message}")]  
  20.         string EchoPostMethod(String message);  
  21.     }  
  22. }  
Listing 8
 
And the implementation of the contract is shown in Listing 9. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8.   
  9. namespace WCF_NewFeatures  
  10. {  
  11.     public class EchoService : IEchoService  
  12.     {  
  13.         #region IEchoService Members  
  14.         public string EchoGetMethod(string message)  
  15.         {  
  16.             string outgoingMessageFormat = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];  
  17.             if (!String.IsNullOrEmpty(outgoingMessageFormat))  
  18.             {  
  19.                 if (outgoingMessageFormat.Equals("json",StringComparison.OrdinalIgnoreCase))  
  20.                 {  
  21.                     WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;  
  22.                 }  
  23.                 else  
  24.                 if (outgoingMessageFormat.Equals("xml", StringComparison.OrdinalIgnoreCase))  
  25.                 {  
  26.                     WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;  
  27.                 }  
  28.             }  
  29.             return "EchoGetMethodJson invoked using HTTP Get method. Message is (Json format) " + message;  
  30.         }  
  31.    
  32.         public string EchoPostMethod(string message)  
  33.         {  
  34.             return "EchoGetMethod invoked using HTTP Post method. Message is " + message;  
  35.         }  
  36.         #endregion  
  37.     }  
  38. }
Listing 9
 
Now if you access to the service using the following URI http://localhost:8080/Services/EchoService/getecho/mymessage?format=xml, you will receive a the response in XML format, and if you request the service using the following URI http://localhost:8080/Services/EchoService/getecho/mymessage?format=json, you will receive the response in Json format.
 
Another good feature of WCF 4.0 to support REST Web services is the error handling support in order to build more robust applications and avoid constructing manually the HTTP response with error message.
 
Now we can use a new class for error handling: WebFaultException<T>. For example, if you want to include error handling in the previous example in order to report an unsupported format, you need to include the code shown in the Listing 10 highlighted in yellow. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8. using System.Net;  
  9.   
  10. namespace WCF_NewFeatures  
  11. {  
  12.     public class EchoService : IEchoService  
  13.     {  
  14.         #region IEchoService Members  
  15.         public string EchoGetMethod(string message)  
  16.         {  
  17.             string outgoingMessageFormat = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];  
  18.             if (!String.IsNullOrEmpty(outgoingMessageFormat))  
  19.             {  
  20.                 if (outgoingMessageFormat.Equals("json",StringComparison.OrdinalIgnoreCase))  
  21.                 {  
  22.                     WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;  
  23.                 }  
  24.                 else  
  25.                 if (outgoingMessageFormat.Equals("xml", StringComparison.OrdinalIgnoreCase))  
  26.                 {  
  27.                     WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;  
  28.                 }  
  29.                 else  
  30.                 {  
  31.                     throw new WebFaultException<string>("Unsupported format "+ outgoingMessageFormat, HttpStatusCode.BadRequest);  
  32.                 }  
  33.             }  
  34.             return "EchoGetMethodJson invoked using HTTP Get method. Message is (Json format) " + message;  
  35.         }  
  36.   
  37.         public string EchoPostMethod(string message)  
  38.         {  
  39.             return "EchoGetMethod invoked using HTTP Post method. Message is " + message;  
  40.         }  
  41.         #endregion  
  42.     }  
  43. }
Listing 10
 
Another good feature in WCF to support REST Web services is the HTTP Caching. WCF comes with a simple model to implement caching through the [AspNetCacheProfile] attribute that you can apply to operations supported by HTTP Get method. This attribute enables specifying an ASP.NET caching profile name for each operation and behind the scenes there's a cache inspector taking care of the handling of the underlying caching implementation.
 

Conclusion

 
In this series of article, I've explained the new features of WCF 4.0 through concepts and examples.
 


Similar Articles