Search This Blog

Tuesday, October 23, 2012

A Known Error in WCF Restful Service

I found a resolution of a commonly occurring error while working with WCF restful services and I copied the entire problem description and its resolution from this blog.

http://blogs.msdn.com/b/justinjsmith/archive/2008/02/15/enablewebscript-uritemplate-and-http-methods.aspx

The text reads as below

A little while ago I ran into an interesting set of errors that may be of interest to you. Consider the following service contract snippet:
[OperationContract]
[WebGet(UriTemplate="foobar/{value}")]
String GetData(String value);

If you add the enableWebScript behavior to an endpoint that is using the WebHttpBinding, you will see this exception when the ServiceHost starts:

System.InvalidOperationException: Endpoints using 'UriTemplate' cannot be used with 'System.ServiceModel.Description.WebScriptEnablingBehavior'.

The reason for this error is rooted in the origin of the enableWebScript behavior. One of it's design objectives was to simplify working with the ASP.NET AJAX stack (Javascript proxy, JSON messages, etc). The AJAX stack doesn't have the equivalent of the UriTempalte type. It simply puts parameters in query strings (gets) and constructs entity bodies (posts). This is the default behavior of the WCF stack when the WebGet / WebInvoke annotations do not have a value for UriTemplate. Since any value of UriTemplate would be incompatible with the ASP.NET AJAX stack, we throw when it's present.

If you want JSON messages from a contract and you want to use the UriTemplate niceness, you can change your contract to:
[OperationContract]
[WebGet(UriTemplate="foobar/{value}", ResponseFormat=WebMessageFormat.Json)]
String GetData(String value);

Then, instead of using the enableWebScript behavior, use the WebHttpBehavior. You'll lose compat with the ASP.NET AJAX client stack (and the JS proxy), but you have the URI you are looking for.

The same is true if you are using the WebInvoke attribute and any HTTP method other than POST. The AJAX client stack only knows GET and POST... 

1 comment:

  1. Thanks. Helped me a lot in my current quest. :-) Ondrej

    ReplyDelete