Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API 2 Controller not working in ASP.NET MVC 5

I'm not sure why but my api route just isn't working? What I do is click on the add controller, select Web API 2 controller with actions using EF (so that it builds it for me) select the model and context and click Add.

WebApiConfig

public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

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

ProductsController (ApiController)

public IQueryable<Product> GetProducts()
    {
        return db.Products;
    }

This would imply that by going to /api/products it would display a json format of products ... it doesn't. What I DO get is a 404: The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. I tried putting a breakpoint in too and that doesn't even get hit. So I'm a little confused.

I do have custom Web Route configs, which I thought could have been the problem, but when commenting them out still this happens. Is scaffolding missing something?

Thanks for any help

like image 331
Ultigma Avatar asked Feb 19 '15 19:02

Ultigma


2 Answers

After creating a new project and creating an API controller a text file popped up (One i decided to close thinkign I knew better) But it does not pop up again once closed.

The Solution

Simply add 2 using statements to Global.asax

using System.Web.Routing;
using System.Web.Http;

and GlobalConfiguration.Configure(WebApiConfig.Register); MUST COME FIRST in the same file under the Application_Start method

protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register); // <--- this MUST be first 
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

Hopefully this can help someone else out

like image 114
Ultigma Avatar answered Oct 23 '22 18:10

Ultigma


A little addition to Ultigma's answer. In your global.asax.cs this:

GlobalConfiguration.Configure(WebApiConfig.Register);

should be prior to this:

RouteConfig.RegisterRoutes(RouteTable.Routes);

The reason is that the default Web Api route "api/{controller}/{action}/{id}" is more specific than the MVC default route "{controller}/{action}/{id}" and should be placed first. If not, a request to /api/products will be treated as a call to a Products method of an Api controller.

like image 1
SVVer Avatar answered Oct 23 '22 19:10

SVVer