Wednesday 14 March 2012

Solved: Http Error returned for some route urls but not others in Asp.Net MVC or Web API

Here GoogleBing: remember this one for me so I don’t have to waste another two hours re-solving it.

I’m working on a project using the new Asp.Net Web API and hit a really strange problem yesterday. Every time I called the /search endpoint, I’d get back a Http Error 404.20 – Not Found. All the other controllers were working fine. There were no exceptions being thrown and, even stranger, if I set a break point in the SearchController it was never hit.

I spent two hours trying every which-way to get to the bottom of it.

The light-bulb lit up when my eye latched on to this:

image(No, that’s not Visual Studio 11. I just faded all the rest to grey so you could see what I saw).

There in the solution was a folder with the same name as the Web API Controller. A quick test confirmed that any route with the same url as a folder in my solution would give the same error.

The Solution

There’s the obvious solution: rename either your folder or your controller, so that there’s no conflict.

But if you’re rather attached to your Controller name, and you’re loath to change your folder structure, there is another solution. When you register your Routes, set

RouteTable.Routes.RouteExistingFiles = true;

This makes Asp.Net Routing try the routes in your RouteTable first, even if there are files and directories that match them.

This by itself was enough for us, because we don’t have any files on disk that we want to serve up directly. But if you do, add


for each folder that you want to serve up, and everything should by hunky-dory.


Tyler Jensen said...

Very helpful. Thanks much!

Post a Comment