Sunday, January 16, 2011

WCF REST IIS Hosting 404 Issue - RESOLVED!

Recently I've been mucking about in the WCF-REST arena and ran into an infuriating problem that kept me busy for almost three days.  Essentially I had created a small WCF REST service, and it worked fine when accessing it from VS2010 debugging, however why I tried to access the version I had published in IIS (IIS7 or IIS7.5) it would show me a 404 error, or the annoying "directory browsing not enabled" error.  Now you'd expect this on the old .NET 3.5 implementations of WCF REST, but in the newer environments you can do a .svc-less implementation of your service that is much cleaner and leads to a very straight-forward code to URL implementation.  I finally found a solution to my problem, and though it was one of those  embarrassingly obvious solutions, I could have gotten three days of my life back if someone would have mentioned their mistake.

Now if you do a Google search on "wcf rest iis hosting" you'll see that quite a few people have been having these issues, and there are answers out there ranging from making sure the AppPool user has the right permissions to ensuring that ASP.NET had been properly installed on IIS.  None of these suggestions worked for me, leading to quite a bit of frustration.  There was one small hint tucked away that eventually tipped me off to the real solution, however I didn't think to check it until today.  On Christopher Deweese's blog he has a great post discussing how to "do" WCF REST in .NET 4.0 and in the comments he mentions "You should not have a virtual folder set up for your paths. You should just deploy the service and let the routes be determined by the application (not at the IIS level)."  This is the key, in your  global ASAX file you'll have a line of code that looks like this: RouteTable.Routes.Add(new ServiceRoute("MyServiceName", new WebServiceHostFactory(), typeof(MyServiceType)));

Now, when you access this from the debugger you'll end up doing so from a URL similar to "http://localhost:[port]/MyServiceName/...", however once you publish your service to it's own IIS application under the Default Web Site you'll get the 404's starting to pop up again trying to access the URL "http://localhost/MyServiceName/..."  The answer to the problem becomes obvious when you notice that "http://localhost/MyServiceName/MyServiceName/..." works.  The "MyServiceName" string within your ServiceRoute(...) is being appended to the root of your application to determine the route to your service.  So to fix this you can simply publish your service to the root of its own site, or make your RouteTable declaration look like this:  RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(MyServiceType)));

I hope this saves you a good bit of time in the future when trying to publish WCF REST to IIS7/7.5 and good luck with your future coding!