All ASP.NET Web API controllers return 404

asp.net Mvcasp.net Mvc-4asp.net Web-Api

asp.net Mvc Problem Overview


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!

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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.

Solution 2 - asp.net Mvc

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

<modules runAllManagedModulesForAllRequests="true" />

to the

<system.webServer>

</system.webServer>

section of web.config

Solution 3 - asp.net Mvc

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!

Solution 4 - asp.net Mvc

Add following line

GlobalConfiguration.Configure(WebApiConfig.Register);

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

Solution 5 - asp.net Mvc

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.

Solution 6 - asp.net Mvc

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(){

Solution 7 - asp.net Mvc

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

Solution 8 - asp.net Mvc

Had this problem. Had to uncheck Precompile during publishing.

Solution 9 - asp.net Mvc

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!

Solution 10 - asp.net Mvc

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);
}

Solution 11 - asp.net Mvc

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.

Solution 12 - asp.net Mvc

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!

Solution 13 - asp.net Mvc

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.

Solution 14 - asp.net Mvc

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.

Solution 15 - asp.net Mvc

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.

Solution 16 - asp.net Mvc

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>

Solution 17 - asp.net Mvc

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!

Solution 18 - asp.net Mvc

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.

Solution 19 - asp.net Mvc

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTed NybergView Question on Stackoverflow
Solution 1 - asp.net MvcEric BishardView Answer on Stackoverflow
Solution 2 - asp.net MvcZenilogixView Answer on Stackoverflow
Solution 3 - asp.net Mvcuser4796368View Answer on Stackoverflow
Solution 4 - asp.net MvcFarhan AnwarView Answer on Stackoverflow
Solution 5 - asp.net MvcAran DekarView Answer on Stackoverflow
Solution 6 - asp.net MvcBRassView Answer on Stackoverflow
Solution 7 - asp.net MvcShakeer HussainView Answer on Stackoverflow
Solution 8 - asp.net Mvcuser7885142View Answer on Stackoverflow
Solution 9 - asp.net MvcTed NybergView Answer on Stackoverflow
Solution 10 - asp.net MvcMorvaelView Answer on Stackoverflow
Solution 11 - asp.net MvcKevin R.View Answer on Stackoverflow
Solution 12 - asp.net Mvck2snowman69View Answer on Stackoverflow
Solution 13 - asp.net MvcRamView Answer on Stackoverflow
Solution 14 - asp.net MvcDavoud ZeiniView Answer on Stackoverflow
Solution 15 - asp.net MvcPavelView Answer on Stackoverflow
Solution 16 - asp.net MvcHartono HalimView Answer on Stackoverflow
Solution 17 - asp.net MvcnuanderView Answer on Stackoverflow
Solution 18 - asp.net MvcTomView Answer on Stackoverflow
Solution 19 - asp.net MvcbafsarView Answer on Stackoverflow