7

Here's my Global.asax

    protected void Application_Start()
    {
        RegisterRoutes();
    }

    private static void RegisterRoutes()
    {
        AreaRegistration.RegisterAllAreas();

        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        GlobalConfiguration.Configure(x => x.MapHttpAttributeRoutes());
        GlobalConfiguration.Configuration.EnsureInitialized();
    }

Here's my Web Api controller

    [RoutePrefix("api/admin/users/")]
    public class UsersController : ApiController
    {
        [Route("get")]
        public IQueryable<User> GetUsers()
        {
            return db.Users;
        }
    }

And here's the error I get when I navigate to localhost:123/api/admin/users/get

The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.

I have no idea what I'm doing wrong here. I believe that I'm doing everything properly for the new WebApi 2.0 way, but I'm missing something.

Thanks in advance.

Update

Here's the stack in-case it helps

at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) 
at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
Matt
  • 6,264
  • 10
  • 54
  • 82

2 Answers2

6

Please remove

    GlobalConfiguration.Configure(x => x.MapHttpAttributeRoutes());

from Global.asax.

And then call MapHttpAttributeRoutes in the WebApiConfig.cs

    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
    }
Feng Zhao
  • 2,977
  • 1
  • 14
  • 20
  • 1
    Just tried this out this morning. Not sure that I understand why the call needs to be made inside of the WebApiConfig.cs but this fixed the problem. Thanks for your help. – Matt Aug 05 '14 at 13:38
  • Is it by convention? What does name of whateverConfig.cs matter? – Igor Be Apr 09 '16 at 21:29
  • Could have something to do with [this answer](http://stackoverflow.com/a/34325083/1516678) - basically the routes must be mapped before GlobalConfiguration.Configure is called. – Alyce Jun 23 '16 at 04:43
3

In my case, I was getting this error because I was configuring Autofac before WebApi:

GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configure(AutofacConfig.Register);

Changing the order got me past that issue:

GlobalConfiguration.Configure(AutofacConfig.Register);
GlobalConfiguration.Configure(WebApiConfig.Register);
Josh M.
  • 26,437
  • 24
  • 119
  • 200