WCF - Supporting raw requests for individual operations
In the post about the raw mode for the WCF Web programming model, I showed how to use a content-type mapper to tell WCF to treat all incoming requests as “raw” requests, so we could map any content, including those supported by the formatter, to a Stream parameter. This is done at the encoder level, so all operations in the contract basically share the same raw mode. But if you want to mix / match operations with “normal” parameters with operations with a stream parameter, then it becomes a problem, like in the contract below. If we don’t use a content-type mapper, requests with JSON or XML content cannot reach the Upload operation; if we do use one (to map incoming requests to raw), requests of that same content-type cannot be made to the Add operation.
- [ServiceContract]
- public class Service
- {
- [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest)]
- public int Add(int x, int y)
- {
- return x + y;
- }
- [WebInvoke]
- public string Upload(Stream data)
- {
- return new StreamReader(data).ReadToEnd();
- }
- }
One possible solution for this is to split the contract in two (and have them as interfaces), have the service implement both interfaces and have two endpoints. This works, but it has the drawback of splitting the URI space between the two contracts, since two endpoints cannot share the same address.
But it’s possible to implement that behavior as well, with a formatter which a trick that will use another encoder to read the input in the format required by the “typed” operations, and we’ll be able to tag the operations for which we can opt-out of the raw format:
- [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest)]
- [NonRaw]
- public int Add(int x, int y)
- {
- return x + y;
- }
The NonRawAttribute class is simply an empty attribute class which implements IOperationBehavior, so I’ll skip it here. The interesting part happens at a new formatter which we’ll implement to do the conversion, and is shown below. When deserializing the request, if the operation with which the formatter is associated it is tagged with the [NonRaw] attribute, we’ll write the message back, and then read with the encoder – which does not have any content-type mapper set. That will create a message tagged with the format corresponding to the request’s Content-Type header, which is what we need for the “typed” operations. There is a big drawback of this process, though – there will be a performance hit (both for execution time and memory usage) for those [NonRaw] operations, since there will be an additional encoding / decoding of the message done in the formatter. For small requests this should not be significant, though.
- public class DualModeFormatter : IDispatchMessageFormatter
- {
- OperationDescription operation;
- IDispatchMessageFormatter originalFormatter;
- MessageEncoder webMessageEncoder;
- BufferManager bufferManager;
- public DualModeFormatter(OperationDescription operation, IDispatchMessageFormatter originalFormatter)
- {
- this.operation = operation;
- this.originalFormatter = originalFormatter;
- this.webMessageEncoder = new WebMessageEncodingBindingElement()
- .CreateMessageEncoderFactory()
- .Encoder;
- this.bufferManager = BufferManager.CreateBufferManager(int.MaxValue, int.MaxValue);
- }
- public void DeserializeRequest(Message message, object[] parameters)
- {
- if (this.operation.Behaviors.Find<NonRawAttribute>() != null)
- {
- ArraySegment<byte> buffer = this.webMessageEncoder.WriteMessage(message, int.MaxValue, bufferManager);
- string contentType = ((HttpRequestMessageProperty)message.Properties[HttpRequestMessageProperty.Name])
- .Headers[HttpRequestHeader.ContentType];
- message = this.webMessageEncoder.ReadMessage(buffer, bufferManager, contentType);
- bufferManager.ReturnBuffer(buffer.Array);
- }
- this.originalFormatter.DeserializeRequest(message, parameters);
- }
- public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
- {
- throw new NotSupportedException("This is a request-only formatter");
- }
- }
We also need to set this formatter, and the easiest way is to create a class derived from WebHttpBehavior for that.
- public class DualModeWebHttpBehavior : WebHttpBehavior
- {
- protected override IDispatchMessageFormatter GetRequestDispatchFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
- {
- IDispatchMessageFormatter originalFormatter = base.GetRequestDispatchFormatter(operationDescription, endpoint);
- return new DualModeFormatter(operationDescription, originalFormatter);
- }
- }
We can now test this code. Notice that we’re sending typed (JSON) request to the Add operation, and both typed (JSON) and untyped (text) to the stream operation.
- static void Main(string[] args)
- {
- string baseAddress = "https://" + Environment.MachineName + ":8000/Service";
- ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
- WebHttpBinding binding = new WebHttpBinding();
- binding.ContentTypeMapper = new RawContentTypeMapper();
- ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(Service), binding, "");
- DualModeWebHttpBehavior behavior = new DualModeWebHttpBehavior();
- behavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;
- endpoint.Behaviors.Add(behavior);
- host.Open();
- Console.WriteLine("Host opened");
- SendRequest(baseAddress + "/Add", "POST", "application/json", "{\"x\":3,\"y\":5}");
- SendRequest(baseAddress + "/Upload", "POST", "application/json", "{\"x\":3,\"y\":5}");
- SendRequest(baseAddress + "/Upload", "POST", "text/plain", "some random text");
- Console.Write("Press ENTER to close the host");
- Console.ReadLine();
- host.Close();
- }
And that’s it. The full code for this post can be found in GitHub at https://github.com/carlosfigueira/WCFSamples/tree/master/MessageFormatter/PerOperationContentTypeMapper.
Comments
- Anonymous
February 08, 2013
Hi Carlos,I have a REST based service returning JSON data using VS 2010. I am using WebHttpbinding, security mode of "TransportCredentialOnly" with clientCredentialType as Basic. In the Servicebehavior, I am using usernameAuth with customUserNamePasswordValidatorType set to use a customer username n pwd validator and userNamePasswordValidationMode="Custom". This is hosted on console app and when i try to navigate to the url, I get a credential pop up asking for a username and password which ties back to the routine I have written in the "customUserNamePasswordValidatorType " above. All this is good.The problem occurs when I host this on my local web server (IIS 7.5) instead of the console app.Using the same config, I get this error below. Note that for hosting on IIS and using REST , I am using System.web.routing to add a serviceroute using the webservicehostfactory (NOT using the .svc approach). Am I missing something here? I tried setting the IIS Authentication for the website to Anonymous which gives the error below. IF I set it to "Basic" I get the pop up for credentials but it does not tie back toe the routine I wrote above. Please let me know.The authentication schemes configured on the host ('Ntlm, Anonymous') do not allow those configured on the binding 'WebHttpBinding' ('Basic'). Please ensure that the SecurityMode is set to Transport or TransportCredentialOnly. Additionally, this may be resolved by changing the authentication schemes for this application through the IIS management tool, through the ServiceHost.Authentication.AuthenticationSchemes property, in the application configuration file at the <serviceAuthenticationManager> element, by updating the ClientCredentialType property on the binding, or by adjusting the AuthenticationScheme property on the HttpTransportBindingElement. - Anonymous
June 27, 2013
Carlos, thank you for this useful information. I was able to get it working for my purposes. A minor problem I had to contend with before resolving this WCF problem was disabling IIS's filename extension filter to prevent it from denying uploads of certain files to my file upload operations.I am using your raw-request code to enable selected REST services for my web application. I inserted this code into myWebServiceHostFactory
, and blindly assigned theWebHttpBinding
to my service; WCF started throwing an unexpected exception when I tried to upload a (bigger than trivially small) file. After several days of researching, debugging and finally, service tracing, I discovered that instead of replacing the binding with the raw formatter, it should be updating the existing binding. This way, the binding configuration can be maintained in the application's web.config file and avoid the errors caused by using a default binding (with its small buffers).I also implemented this by modifying theWebServiceHostFactory
that is responsible for instantiating and hosting my service classes. It now recognizes a[RawContentServiceAttribute]
on the service class, to insert theDualModeFormatter
, and a[RawContentOperationAttribute]
on the raw data operation method to actually use the new formatter on only the operations that need it. This limits any performance effects to a few unmarked operations in a single service. To enable this functionality now, I only need to tag my service classes and methods with these attributes.Thanks again for this educational article.