33

我刚刚在我的 MVC 4 应用程序中更新了我的 Web API 包,以便我可以使用属性路由。当我添加时, config.MapHttpAttributeRoutes()我收到一条错误消息,显示“对象尚未初始化。确保在所有其他初始化代码之后在应用程序的启动代码中调用 HttpConfiguration.EnsureInitialized()。” 如果我删除config.MapHttpAttributeRoutes()Route 属性,一切都会像以前一样工作。如何解决此错误?

这是我的 WebApiConfig 类:

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 }
            );



            // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
            // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
            // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
            //config.EnableQuerySupport();
        }
    }

以及错误详情:

该对象尚未初始化。确保在所有其他初始化代码之后在应用程序的启动代码中调用 HttpConfiguration.EnsureInitialized()。

说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.InvalidOperationException:对象尚未初始化。确保在所有其他初始化代码之后在应用程序的启动代码中调用 HttpConfiguration.EnsureInitialized()。

源错误:

在执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常起源和位置的信息。

堆栈跟踪:

[InvalidOperationException: The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.]
   System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() +127
   System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) +99
   System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext) +191
   System.Web.Routing.RouteCollection.GetRouteData(HttpContextBase httpContext) +233
   System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context) +60
   System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e) +82
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
4

2 回答 2

75

在 Global.asax 中,Application_Start 事件需要从

WebApiConfig.Register(GlobalConfiguration.Configuration);

到:

GlobalConfiguration.Configure(WebApiConfig.Register);
于 2013-10-24T20:16:20.133 回答
-1

注释掉或删除以下代码行WebApiConfig

config.MapHttpAttributeRoutes();
于 2015-05-18T21:58:37.750 回答