404 Error in WCF RESTful Services

Recently I’ve been developing a WCF RESTful service. The service included a method to download / upload some files to / and from a backend database. The UriTemplate was something like “/downloads/{filename}.txt”. I was surprised that when I try to download for example test.txt, I was hit by a 404 not found error. When debugging the method never even got hit.

I suddenly realized that when I browser to http://myserver/myservice.svc/downloads/test.txt, IIS actually tries to route the request to a physical file rather than routing the request to the service itself. This is what gives me a 404 error as there is not text file with that path. Thanks to this blog post I got the solution, and it was extremely simple. Just add this line to your Global.asax Application_Start method

Of course if you use another factory you should replace WebServiceHostFactory with yours, but this is the default. And that’s it! Any path requested under your service will be routed handled by your service class and not the IIS. A nice catch is that your service will be root. So to access the above method you won’t request http://myserver/myservice.svc/downloads/test.txt, but instead you’ll request http://myserver/downloads/test.txt. This could make a great confusion if you publish your service to a web application that contains other services or even web pages. To handle this, in the ServiceRoute constructor, instead of having the first parameter as an empty string add you desirable prefix. For example if we use

The request URL would be http://myserver/MyRESTService/downloads/test.txt, which will allow you to access other resources on the same server, and in most cases more aesthetic than having a .svc in your service address.So even if you don’t face the 404 issue I recommend adding this routing in your global.asax.