Thursday, 16 September 2010

WCF URI Template Url-Encoded Character Issues

I've been playing around with RESTFul services in WCF following by the MSDN topic, and have found the guide to be both extremely helpful, and the overall support provided to be excellent.  If you've been writing WCF services for your cloud service offerings, or even just AJAX methods for web-page code, you should find the migration over to RESTful services relatively easy to manage.

It also increases the accessibility of your services a huge amount - very basic jQuery code can be used, for example, to bind to these services.

However, there are some issues surrounding the types of values for parameters that can be bound in either a path or query string segment - and it's all down to some url-encoded characters, and how they get interpreted (or rather not interpreted) before being serialised into method parameters.

The following example is taken from a Microsoft Connect bug that I have posted:

Setup a project to host a WCF .svc and create a method with two parameters:

[WebGet(UriTemplate = "{willfail}?willwork={willwork}")]

[OperationContract]

public string Foo(string willfail, string willwork)

{

Trace.WriteLine("willfail: " + willfail);

Trace.WriteLine("willwork: " + willwork);

string toreturn = 

	string.Format("willfail: {0}. willwork : {1}", 

			willfail, willwork);

return toreturn;

}


In my example, I set the service to be hosted in Asp.Net under IIS (optional, as it turns out) - and I'm using the zero-configuration WebServiceHostFactory factory in the .svc file.


Now, after building, start up a browser and browse to the url that the service is configured on - e.g http://localhost/[baseuriofservice]/[svcfile.svc]/c%23?willwork=c%23.  '%23' is Url-Encoding-speak for '#'.


What you expect to see is "willfail: c#. willwork : c#".


What you actually see is "willfail: c. willwork: c#".


So, when url-encoded characters appear in path segments bound to parameters, they won't always be read correctly (incidentally '%20' is read correctly); but it appears that query-string ones will.


As I mentioned, I posted an Connect bug under the title 'WCF UriTemplate Strips Some UrlEncoded characters from bound path segment' - and it turns out that this behaviour doesn't just affect WCF, or even Asp.Net (since the MS investigator also tried self-hosting the service and it still fails).


Even better news, however, is that this bug has been marked as fixed - so hopefully in the next framework version, we can expect to be able to use path segments with the whole gamut of URL-encodings!


This is one in the eye for Ayende Rahien - who blogged very recently about Connect failing all over the place.

No comments:

Post a Comment