Saturday, January 29, 2011

WCF REST service with custom http header check in .NET 4

This is the posting I initially intended to write when I started writing WCF REST and .NET 4.0.

This posting outlines how to make a simple http header check in the WCF REST based service and depending on the the outcome of the header evaluation either return the result or throw an WebFaultException.

This WCF service is built using .NET 4.0 only without using the WCF REST starter kit (see more information here REST in Windows Communication Foundation (WCF) and here WCF REST Starter Kit Preview 2.


Start out by making a new project in Visual Studio, choose "Online Template" and select the "WCF" sub category. Select "WCF REST Service Template 40".




Change the code of the Service1.cs file to look like the following.


using System.Net;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WcfRestService1
{
 // Start the service and browse to http://<machine_name>:<port>/Service1/help to view the service's generated help page
 // NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want
 // a single instance of the service to process all calls. 
 [ServiceContract]
 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
 public class Service1
 {
  [WebGet(UriTemplate = "{id}")]
  public List<SampleItem> GetProductById(string id)
  {
   if (WebOperationContext.Current.IncomingRequest.Headers["MyCustomHttpHeader"] == null) 
    throw new WebFaultException<string>("The custom httpheader 'MyCustomHttpHeader' has not been set.", HttpStatusCode.BadRequest);
   
   return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Product1" } };
  }
 }
}

Build the solution and try to access the url http://localhost:some_random_dev_web_server_port/Service1/GetProductById?id=1





This was kind of expected, but notice how neat this is tying in with the http request return codes.

If we look at this in Fiddler we will see the following.



As expected according to our code in the service 


if (WebOperationContext.Current.IncomingRequest.Headers["MyCustomHttpHeader"] == null) 
                throw new WebFaultException<string>("The custom httpheader 'MyCustomHttpHeader' has not been set.", HttpStatusCode.BadRequest);


If we now use the Request Builder in Fiddler and add the custom http header "MyCustomHttpHeader" we will see the following result in Fiddler.




If you want to let headers flow back and forth between clients and the services your best option is to add some new classes implementing the interfaces IClientMessageInspector, IEndpointBehavior and if you want this to be configurable from the .config file you need to extend the base class BehaviorExtensionElement.

You can see a sample implementation here WCF REST client using custom http headers
Post a Comment