Share via


enableWebScript, UriTemplate, and HTTP methods

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...

Comments

  • Anonymous
    April 10, 2008
    Looks like this is an interesting topic to a lot of people since part 1 of this series made it to the

  • Anonymous
    May 13, 2008
    The comment has been removed

  • Anonymous
    March 23, 2009
    Thanks for explaining this error. Can't the enableWebScript behavior be modified to overcome this issue?

  • Anonymous
    December 02, 2009
    I have the following code snippet: [OperationContract] [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json, UriTemplate="/Decrypt")] string Decrypt(string interactive); It throws the above error.  I am trying to get JSON to work on a WCF web service and am running in circles!  Any suggestions?