WCF Extensibility – Operation Selectors
This post is part of a series about WCF extensibility points. For a list of all previous posts and planned future ones, go to the index page .
We’re now entering the realm of the less used extensibility points for the WCF runtime. Operation selectors could well be left as an internal implementation detail for WCF, but for some reason the designers decided to make them public (I think the guideline back then was if anyone can come up with a scenario where a user would use it, then WCF would expose a hook for that). The server selector (IDispatchOperationSelector) is actually interesting to have as a public hook, as the whole UriTemplate model for REST services was built on top of it – basically, the selector knows about the HTTP method and URI templates for each service operation, and based on those properties of incoming messages it can call the appropriate operation. For “normal” (i.e., SOAP) endpoints, the operation selector implementation (which happens to be internal) is based on the addressing of the binding – in most of the cases it simply matches the Action header of the message with a map of action to the operation names.
The client operation selector (IClientOperationSelector) is another story. The client selector receives the method invoked by the client (the System.Reflection.MethodBase object) and it must return an operation name which will be used by the WCF runtime to retrieve the actual client operation from the client runtime. I’ve tried for a while to think of any scenario where one would actually want to call one method in the proxy and have another operation be executed (besides some practical joke scenario where one would swap Add for Subtract in a calculator), but I just can’t think of any. Even searching on Bing or Google doesn’t show any real scenarios where a client selector is used. But well, WCF is extensible, so let’s let people choose their client operations as well .
Public implementations in WCF
- WebHttpDispatchOperationSelector (server): The dispatch implementation where the UriTemplate magic happens for WCF REST endpoints.
There are no public implementations for IClientOperationSelector, only an internal one which simply returns the operation name of the method being called.
Interface declaration
- public interface IDispatchOperationSelector
- {
- string SelectOperation(ref Message message);
- }
- public interface IClientOperationSelector
- {
- bool AreParametersRequiredForSelection { get; }
- string SelectOperation(MethodBase method, object[] parameters);
- }
The dispatch operation selector is quite simple – on SelectOperation you get the message, you return the operation name. In most cases the operation can be selected based on information on the message header (e.g., the Action header for SOAP endpoints) or the message properties (e.g., the HTTP request property attached to the message). There are scenarios, however, where the routing to the operation needs to be done based on the message contents, so the message is passed by reference – if it needs to be consumed by the operation selector, it can recreated it to hand it back to the WCF pipeline.
On the client side the AreParametersRequiredForSelection is used to determine whether the response to SelectOperation can be cached or not – if the parameters are not required, the WCF runtime will only call SelectOperation once per method in the proxy, otherwise every time a proxy call is made the selector will be invoked again.
How to add operation selectors
At the server side: the operation selector is a property of the DispatchRuntime object. It’s typically accessed via the endpoint dispatcher in a call to IEndpointBehavior.ApplyDispatchBehavior.
- public class MyEndpointBehavior : IEndpointBehavior
- {
- public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
- {
- endpointDispatcher.DispatchRuntime.OperationSelector = new MyOperationSelector();
- }
- }
- public class MyOperationSelector : IDispatchOperationSelector
- {
- public string SelectOperation(ref Message message)
- {
- string action = message.Headers.Action;
- return action.Substring(action.LastIndexOf('/') + 1);
- }
- }
At the client side: the operation selector is a property of the ClientRuntime object, and is typically accessed via the implementation of IEndpointBehavior.ApplyClientBehavior.
- public class MyEndpointBehavior : IEndpointBehavior
- {
- public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
- {
- clientRuntime.OperationSelector = new MyClientOperationSelector();
- }
- }
- public class MyClientOperationSelector : IClientOperationSelector
- {
- public bool AreParametersRequiredForSelection
- {
- get { return false; }
- }
- public string SelectOperation(MethodBase method, object[] parameters)
- {
- return method.Name;
- }
- }
Real world scenario: Support for X-HTTP-Method-Override in REST endpoints
This issue came from the forum. REST services we use HTTP verbs (methods) to determine the action to be applied to the resource. For example, a GET request to /Contacts/1 would return the contact with id 1, while DELETE /Contacts/1 would remove that same contact from the repository. This is a great – and simple – model, but there are some browsers, proxies, firewalls or even some web service platforms which don’t support the full set of verbs (rejecting anything other than GET and POST). In order to overcome this problem, some platforms (such as ASP.NET MVC and Google Data) started supporting a new HTTP header or field, called X-HTTP-Method-Override, which contain the actual method which should be used by the service to access the resource. The WCF REST API doesn’t support this override natively, but that doesn’t preclude us from using an extensibility point to enable it.
Implementing the support for X-HTTP-Method-Override is nothing but a matter of replacing the operation selector (based on methods and URI templates) used by REST endpoints with our own, which is aware of this new header. When the IDispatchOperationSelector.SelectOperation method is called, we can check if the incoming request contained the override header, and if so, we can update the incoming message properties to let the original selector chose the appropriate operation.
For this example I’ll reuse the contact manager service from the message inspectors post – it contains the different operations which differ based on the HTTP verb of the incoming request, so it’s perfect for this issue. And before I start, the usual disclaimer – this is a sample for illustrating the topic of this post, this is not production-ready code. I tested it for a few contracts and it worked, but I cannot guarantee that it will work for all scenarios (please let me know if you find a bug or something missing). Also, for simplicity sake it doesn’t have a lot of error handling which a production-level code would. Also, the contact manager is all stored in memory, a “real” one would have a backing database or something more “persistent”.
One small parenthesis: the link below for the code in this post contains the version shown here in C# and also a version in VB.NET which does the same thing; if you’re a VB developer, you can check the MSDN code samples out.
The contracts and service implementation are exactly the same as the one from before (I removed the version for Text, as it didn’t add any value to this topic):
- [DataContract]
- public class Contact
- {
- [DataMember]
- public string Id { get; set; }
- [DataMember]
- public string Name { get; set; }
- [DataMember]
- public string Email { get; set; }
- [DataMember]
- public string[] Telephones { get; set; }
- }
- [ServiceContract]
- public interface IContactManager
- {
- [WebInvoke(
- Method = "POST",
- UriTemplate = "/Contacts",
- ResponseFormat = WebMessageFormat.Json)]
- string AddContact(Contact contact);
- [WebInvoke(
- Method = "PUT",
- UriTemplate = "/Contacts/{id}",
- ResponseFormat = WebMessageFormat.Json)]
- void UpdateContact(string id, Contact contact);
- [WebInvoke(
- Method = "DELETE",
- UriTemplate = "/Contacts/{id}",
- ResponseFormat = WebMessageFormat.Json)]
- void DeleteContact(string id);
- [WebGet(UriTemplate = "/Contacts", ResponseFormat = WebMessageFormat.Json)]
- List<Contact> GetAllContacts();
- [WebGet(UriTemplate = "/Contacts/{id}", ResponseFormat = WebMessageFormat.Json)]
- Contact GetContact(string id);
- }
- public class ContactManagerService : IContactManager
- {
- static List<Contact> AllContacts = new List<Contact>();
- static int currentId = 0;
- static object syncRoot = new object();
- public string AddContact(Contact contact)
- {
- int contactId = Interlocked.Increment(ref currentId);
- contact.Id = contactId.ToString(CultureInfo.InvariantCulture);
- lock (syncRoot)
- {
- AllContacts.Add(contact);
- WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Created;
- }
- return contact.Id;
- }
- public void UpdateContact(string id, Contact contact)
- {
- contact.Id = id;
- lock (syncRoot)
- {
- int index = this.FetchContact(id);
- if (index >= 0)
- {
- AllContacts[index] = contact;
- }
- }
- }
- public void DeleteContact(string id)
- {
- lock (syncRoot)
- {
- int index = this.FetchContact(id);
- if (index >= 0)
- {
- AllContacts.RemoveAt(index);
- }
- }
- }
- public List<Contact> GetAllContacts()
- {
- List<Contact> result;
- lock (syncRoot)
- {
- result = AllContacts.ToList();
- }
- return result;
- }
- public Contact GetContact(string id)
- {
- Contact result;
- lock (syncRoot)
- {
- int index = this.FetchContact(id);
- result = index < 0 ? null : AllContacts[index];
- }
- return result;
- }
- private int FetchContact(string id)
- {
- int result = -1;
- for (int i = 0; i < AllContacts.Count; i++)
- {
- if (AllContacts[i].Id == id)
- {
- result = i;
- break;
- }
- }
- if (result < 0)
- {
- WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
- }
- return result;
- }
- }
Now for the behavior used to set up the operation selector. The behavior wraps the original operation selector from the endpoint, so it needs to be added after the WebHttpBehavior (which will add the first selector to the runtime) – see the discussion about wrapping internal objects at the post about formatters).
- public class HttpOverrideBehavior : IEndpointBehavior
- {
- public const string HttpMethodOverrideHeaderName = "X-HTTP-Method-Override";
- public const string OriginalHttpMethodPropertyName = "OriginalHttpMethod";
- public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
- {
- }
- public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
- {
- }
- public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
- {
- endpointDispatcher.DispatchRuntime.OperationSelector = new HttpOverrideOperationSelector(endpointDispatcher.DispatchRuntime.OperationSelector);
- }
- public void Validate(ServiceEndpoint endpoint)
- {
- }
- }
And the selector itself. As I mentioned before, The first thing the selector will do is to try to fetch the HttpRequestMessageProperty from the message properties – if the message was received using HTTP, it will contain information about the HTTP verb and headers in the request. It will then try to find the X-HTTP-Method-Override header, and if it’s present, it will update the message property with the method override. For completeness sake, this selector also adds a new property to the message with the original HTTP verb from the request (if the service needs this information somehow). Finally, the selector delegates the selection to the original selector, which will then use that information to route the incoming request to the appropriate method.
- class HttpOverrideOperationSelector : IDispatchOperationSelector
- {
- private IDispatchOperationSelector originalSelector;
- public HttpOverrideOperationSelector(IDispatchOperationSelector originalSelector)
- {
- this.originalSelector = originalSelector;
- }
- public string SelectOperation(ref Message message)
- {
- if (message.Properties.ContainsKey(HttpRequestMessageProperty.Name))
- {
- HttpRequestMessageProperty reqProp;
- reqProp = (HttpRequestMessageProperty)message.Properties[HttpRequestMessageProperty.Name];
- string httpMethodOverride = reqProp.Headers[HttpOverrideBehavior.HttpMethodOverrideHeaderName];
- if (!String.IsNullOrEmpty(httpMethodOverride))
- {
- message.Properties[HttpOverrideBehavior.OriginalHttpMethodPropertyName] = reqProp.Method;
- reqProp.Method = httpMethodOverride;
- }
- }
- return this.originalSelector.SelectOperation(ref message);
- }
- }
Finally, the test code to wrap it all together. The code is very similar to the one for the message inspectors post, with a few differences: the new behavior (HttpOverrideBehavior) is added after the REST ((WebHttp) behavior, and after sending requests with the “real” HTTP verb it will send some additional requests using POST, but using the HTTP override method to route it to different operations.
- static void Main(string[] args)
- {
- string baseAddress = "https://" + Environment.MachineName + ":8000/Service";
- ServiceHost host = new ServiceHost(typeof(ContactManagerService), new Uri(baseAddress));
- ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IContactManager), new WebHttpBinding(), "");
- endpoint.Behaviors.Add(new WebHttpBehavior());
- endpoint.Behaviors.Add(new HttpOverrideBehavior());
- host.Open();
- Console.WriteLine("Host opened");
- string johnId = SendRequest(
- "POST",
- baseAddress + "/Contacts",
- "application/json",
- CreateJsonContact(null, "John Doe", "john@doe.com", "206-555-3333"));
- string janeId = SendRequest(
- "POST",
- baseAddress + "/Contacts",
- "application/json",
- CreateJsonContact(null, "Jane Roe", "jane@roe.com", "202-555-4444 202-555-8888"));
- Console.WriteLine("All contacts");
- SendRequest("GET", baseAddress + "/Contacts", null, null);
- Console.WriteLine("Updating Jane");
- SendRequest(
- "PUT",
- baseAddress + "/Contacts/" + janeId,
- "application/json",
- CreateJsonContact(janeId, "Jane Roe", "jane@roe.org", "202-555-4444 202-555-8888"));
- Console.WriteLine("All contacts");
- SendRequest("GET", baseAddress + "/Contacts", null, null);
- Console.WriteLine("Deleting John");
- SendRequest("DELETE", baseAddress + "/Contacts/" + johnId, null, null);
- Console.WriteLine("Is John still here?");
- SendRequest("GET", baseAddress + "/Contacts/" + johnId, null, null);
- Console.WriteLine("Adding John again");
- johnId = SendRequest(
- "POST",
- baseAddress + "/Contacts",
- "application/json",
- CreateJsonContact(null, "John Doe", "john@doe.com", "206-555-3333"));
- Console.WriteLine("Updating John, now using X-HTTP-Method-Override");
- Dictionary<string, string> overrideWithPut = new Dictionary<string, string>();
- overrideWithPut.Add("X-HTTP-Method-Override", "PUT");
- SendRequest(
- "POST",
- baseAddress + "/Contacts/" + johnId,
- "application/json",
- CreateJsonContact(johnId, "John Doe Updated", "john@doe.com", "206-555-3333"),
- overrideWithPut);
- Console.WriteLine("All contacts");
- SendRequest("GET", baseAddress + "/Contacts", null, null);
- Console.WriteLine("Deleting Jane, using X-HTTP-Method-Override");
- Dictionary<string, string> overrideWithDelete = new Dictionary<string, string>();
- overrideWithDelete.Add("X-HTTP-Method-Override", "DELETE");
- SendRequest("POST", baseAddress + "/Contacts/" + janeId, "application/json", "", overrideWithDelete);
- Console.WriteLine("All contacts");
- SendRequest("GET", baseAddress + "/Contacts", null, null);
- Console.WriteLine("Press ENTER to close");
- Console.ReadLine();
- host.Close();
- }
Coming up
Operation invokers, for both synchronous and asynchronous operations.
Carlos Figueira
https://blogs.msdn.com/carlosfigueira
Twitter: @carlos_figueira https://twitter.com/carlos_figuei