ASP.NET C# Web API resource not found error

Viewed 92

I am learning Web API and have added an API Controller in my asp.net mvc5 web project, I am constantly getting resource not found error. The project is building successfully. Please point out mistakes I might be making...

following is my router config ,global.asax and controller.cs code for WebApi

RouteConfig.cs

namespace DemoWebAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Global.asax.cs

namespace DemoWebAPI
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
}

ValueController.cs (API controller)

namespace DemoWebAPI.Controllers
{
    public class ValueController : ApiController
    {
        public IHttpActionResult Get()
        {
            return Ok(1);
        }
    }
}

"https://localhost:44370/api/value" is the url scheme i use to call web api, but it persistenly "The resource cannot be found."

1 Answers

The order is important in global.asax file. Moving GlobalConfiguration.Configure(WebApiConfig.Register); before RouteConfig.RegisterRoutes(RouteTable.Routes); resolves the issue.

Related