这是我的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();
}
这是我的Web Api控制器
[RoutePrefix("api/admin/users/")]
public class UsersController : ApiController
{
[Route("get")]
public IQueryable<User> GetUsers()
{
return db.Users;
}
}
这是我导航到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.
我不知道我在这里做错了什么。我相信我正在为新的WebApi 2.0方式做正确的事情,但我错过了一些东西。
提前致谢。
更新
这是有帮助的堆栈
at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request)
at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
答案 0 :(得分:6)
请删除
GlobalConfiguration.Configure(x => x.MapHttpAttributeRoutes());
来自 Global.asax 。
然后在 WebApiConfig.cs
中致电MapHttpAttributeRoutes
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
}
答案 1 :(得分:3)
就我而言,我收到此错误是因为我在WebApi之前配置了Autofac:
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configure(AutofacConfig.Register);
改变顺序让我超越了这个问题:
GlobalConfiguration.Configure(AutofacConfig.Register);
GlobalConfiguration.Configure(WebApiConfig.Register);