Why can't navigate to web api controller

1110 picture 1110 · Aug 25, 2014 · Viewed 27.1k times · Source

I use Web API for the first time to connect my mobile app to Web API.
I have MVC 5 project and I have created API folder and inside I have created ProductsController.

namespace DDD.WebUI.API
{
    public class ProductsController : ApiController
    {
        public string GetAllProducts()
        {
            return "Hello From WebAPI";
        }

    }
}

And I have tried to access this method from browser:

http://localhost:21879/DDD.WebUI/API/products/GetAllProducts

But I get 404.
It's probably something stupid but can't figure it :(
UPDATE

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
               name: "DefaultApi",
               url: "API/{controller}/{action}/{id}",
               defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
           );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );



        }

UPDATE 2
I have a little progress: I have update Application_Start() with:

GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);

In WebApiConfig I have:

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

I still store API controller in Project/Api/ProductsController But now I can access it but still can't get value from it:

http://localhost:21879/api/products/getallproducts

But error I get is:

<Error>
<Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'GSL.WebUI.Api.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>

Answer

Kevin picture Kevin · Oct 8, 2017

I had the same problem. Watch the order in which you register your routes in Global.asax.cs.

This works:

GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);

This doesn't:

RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);