67
votes

I'm trying to get an API Controller to work inside an ASP.NET MVC 4 web app. However, every request results in a 404 and I'm stumped. :/

I have the standard API controller route from the project template defined like:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

The registration is invoked in Global.asax:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    // Register API routes
    WebApiConfig.Register(GlobalConfiguration.Configuration);

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

I have a basic API controller like this:

namespace Website.Controllers
{
    public class FavoritesController : ApiController
    {       
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new [] { "first", "second" };
        }

        // PUT api/<controller>/5
        public void Put(int id)
        {

        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {

        }
    }
}

Now, when I browse to localhost:59900/api/Favorites I expect the Get method to be invoked, but instead I get a 404 status code and the following response:

<Error>
   <Message>
       No HTTP resource was found that matches the request URI 'http://localhost:59900/api/Favorites'.
   </Message>
   <MessageDetail>
      No type was found that matches the controller named 'Favorites'.
   </MessageDetail>
</Error>

Any help would be greatly appreciated, I'm losing my mind a little bit over here. :) Thanks!

19
Have you tried testing your routes with Phil Haack's Route Tester? haacked.com/archive/2008/03/13/url-routing-debugger.aspxRobert Harvey
The route tester says the /api/Favorites request matches the api/{controller}/{id} route pattern. However, there are other external routes that match higher up in the list. Perhaps those routes are intercepting my requests...Ted Nyberg
Cleared all other routes, still same result. :(Ted Nyberg
why are you overriding Application_Start? By default that method will register what you have in your overridden method. Maybe the routes being registered twice is causing problems.nitewulf50
I have an abstract base class that I'm inheriting. I've tried skipping the inheritance, but the result remains the same. Thanks for the help, though! I'll edit the question to get rid of any confusion. :)Ted Nyberg

19 Answers

136
votes

One thing I ran into was having my configurations registered in the wrong order in my GLobal.asax file for instance:

Right Order:

AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);

Wrong Order:

AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register(GlobalConfiguration.Configuration);

Just saying, this was my problem and changing the order is obvious, but sometimes overlooked and can cause much frustration.

14
votes

Had essentially the same problem, solved in my case by adding:

<modules runAllManagedModulesForAllRequests="true" />

to the

<system.webServer>

</system.webServer>

section of web.config

12
votes

I have been working on a problem similar to this and it took me ages to find the problem. It is not the solution for this particular post, but hopefully adding this will save someone some time trying to find the issue when they are searching for why they might be getting a 404 error for their controller.

Basically, I had spelt "Controller" wrong at the end of my class name. Simple as that!

10
votes

Add following line

GlobalConfiguration.Configure(WebApiConfig.Register);

in Application_Start() function in Global.ascx.cs file.

7
votes

I had the same problem, then I found out that I had duplicate api controller class names in other project and despite the fact that the "routePrefix" and namespace and project name were different but still they returned 404, I changed the class names and it worked.

5
votes

Similar problem with an embarrassingly simple solution - make sure your API methods are public. Leaving off any method access modifier will return an HTTP 404 too.

Will return 404:

List<CustomerInvitation> GetInvitations(){

Will execute as expected:

public List<CustomerInvitation> GetInvitations(){
3
votes

Create a Route attribute for your method.

example

        [Route("api/Get")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

You can call like these http://localhost/api/Get

2
votes

I'm a bit stumped, not sure if this was due to an HTTP output caching issue.

Anyways, "all of a sudden it started working properly". :/ So, the example above worked without me adding or changing anything.

Guess the code just had to sit and cook overnight... :)

Thanks for helping, guys!

2
votes

For reasons that aren't clear to me I had declared all of my Methods / Actions as static - apparently if you do this it doesn't work. So just drop the static off

[AllowAnonymous]
[Route()]
public static HttpResponseMessage Get()
{
    return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}

Became:-

[AllowAnonymous]
[Route()]
public HttpResponseMessage Get()
{
    return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
1
votes

Check that if your controller class has the [RoutePrefix("somepath")] attribute, that all controller methods also have a [Route()] attribute set.

I've run into this issue as well and was scratching my head for some time.

1
votes

I'm going to add my solution here because I personally hate the ones which edit the web.config without explaining what is going on.

For me it was how the default Handler Mappings are set in IIS. To check this...

  1. Open IIS Manager
  2. Click on the root node of your server (usually the name of the server)
  3. Open "Handler Mappings"
  4. Under Actions in the right pane, click "View ordered list"

This is the order of handlers that process a request. If yours are like mine, the "ExtensionlessUrlHandler-*" handlers are all below the StaticFile handler. Well that isn't going to work because the StaticFile handler has a wildcard of * and will return a 404 before even getting to an extensionless controller.

So rearranging this and moving the "ExtensionlessUrlHandler-*" above the wildcard handlers of TRACE, OPTIONS and StaticFile will then have the Extensionless handler activated first and should allow your controllers, in any website running in the system, to respond correctly.

Note: This is basically what happens when you remove and add the modules in the web.config but a single place to solve it for everything. And it doesn't require extra code!

1
votes
WebApiConfig.Register(GlobalConfiguration.Configuration);

Should be first in App_start event. I have tried it at last position in APP_start event, but that did not work.

1
votes

Had this problem. Had to uncheck Precompile during publishing.

0
votes

Add this to <system.webServer> in your web.config:

<handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
    <remove name="OPTIONSVerbHandler"/>
    <remove name="TRACEVerbHandler"/>
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler"
        preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>

Adding <modules runAllManagedModulesForAllRequests="true" /> also works but is not recommended due performance issues.

0
votes

I have solved similar problem by attaching with debugger to application init. Just start webserver (for example, access localhost), attach to w3wp and see, if app initialization finished correctly. In my case there was exception, and controllers was not registered.

0
votes

I had the same 404 issue and none of the up-voted solutions here worked. In my case I have a sub application with its own web.config and I had a clear tag inside the parent's httpModules web.config section. In IIS all of the parent's web.config settings applies to sub application.

<system.web>    
  <httpModules>
    <clear/>
  </httpModules>
</system.web>

The solution is to remove the 'clear' tag and possibly add inheritInChildApplications="false" in the parent's web.config. The inheritInChildApplications is for IIS to not apply the config settings to the sub application.

<location path="." inheritInChildApplications="false">
  <system.web>
  ....
  <system.web>
</location>
0
votes

I have dozens of installations of my app with different clients which all worked fine and then this one just always returned 404 on all api calls. It turns out that when I created the application pool in IIS for this client it defaulted to .net framework 2.0 instead of 4.0 and I missed it. This caused the 404 error. Seems to me this should have been a 500 error. Very misleading Microsoft!

0
votes

I had this problem: My Web API 2 project on .NET 4.7.2 was working as expected, then I changed the project properties to use a Specific Page path under the Web tab. When I ran it every time since, it was giving me a 404 error - it didn't even hit the controller.

Solution: I found the .vs hidden folder in my parent directory of my VS solution file (sometimes the same directory), and deleted it. When I opened my VS solution once more, cleaned it, and rebuilt it with the Rebuild option, it ran again. There was a problem with the cached files created by Visual Studio. When these were deleted, and the solution was rebuilt, the files were recreated.

0
votes

If you manage the IIS and you are the one who have to create new site then check the "Application Pool" and be sure the CLR version must be selected. In my situation, it had been selected "No Managed Code". After changed to v4.0 it started to work.