enableWebScript, UriTemplate, and HTTP methods

Published 15 February 08 03:55 PM | justinjsmith 

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

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Kirk Allen Evans's Blog said on April 10, 2008 10:33 AM:

Looks like this is an interesting topic to a lot of people since part 1 of this series made it to the

# Nader said on May 14, 2008 5:05 AM:

In your MIX2008 presentation, you wrote this:

Uri address = new Uri("http://localhost:2000");

UriTemplate template = new UriTemplate("{artist}/{album}");

Uri boundUri = template.BindByPosition(address, "Northwind", "Overdone");

Console.WriteLine(address.ToString());

The last line must been changed to:

Console.WriteLine(boundUri.ToString());

# Mot said on March 23, 2009 9:02 AM:

Thanks for explaining this error.

Can't the enableWebScript behavior be modified to overcome this issue?

Leave a Comment

(required) 
(optional)
(required) 
Page view tracker