ASP.NET MVC WebAPI 404 error
I was experiencing this problem.
I tried editing my WebApiConfig.cs
to meet a number of recommendations here and code samples elsewhere. Some worked, but it didn't explain to why the route was not working when WebApiConfig.cs
was coded exactly as per the MS template WebApi project.
My actual problem was that in manually adding WebApi
to my project, I had not followed the stock order of configuration calls from Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// This is where it "should" be
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
// The WebApi routes cannot be initialized here.
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
I could make guesses about why this is, but I didn't investigate further. It wasn't intuitive to say the least.
The problem is in your routing configuration. Mvc
routing is different from WebApi
routing.
Add reference to System.Web.Http.dll
, System.Web.Http.Webhost.dll
and System.Net.Http.dll
and then configure your API routing as follows:
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
Ensure the following things
1.) Ensure that your IIS is configured with .NET 4.5 or 4.0 if your web api is 4.5 install 4.5 in IIS
run this command in command prompt with administrator privilege
C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis.exe -i
2.) Change your routing to
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
and make request with Demo/Get (where demo is your controller name)
if the 1,2 are not working try 3
3.) Add following configuration in web.config file
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>