161

I've installed Visual Studio 2013 and when I run my app I get the error below.

I've got no idea as to where I'm to initialized this object.

What to do?

 Server Error in '/' Application. The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.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. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [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() +101 System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) +63 System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext) +107 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 Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408 

This is for AlumCloud

0

16 Answers 16

257

If you do it at the end of Application_Start it will be too late, as WebApiConfig.Register has been called.

The best way to resolve this is to use new initialization method by replacing in Global.asax :

WebApiConfig.Register(GlobalConfiguration.Configuration); 

by

GlobalConfiguration.Configure(WebApiConfig.Register); 
Sign up to request clarification or add additional context in comments.

5 Comments

Based on Microsoft documentation this should be the right way to do it. asp.net/web-api/overview/web-api-routing-and-actions/…
I've been migrating an mvc app, when the api routes weren't working, adding this and MapHttpAttributeRoutes brought it all to life.
But what in case if u have WebApiConfig non-static class?
@GeorgyGrigoryev : you can just instantiate it inside the action like so: GlobalConfiguration.Configure(config => new WebApiConfig().Register(config));
@cmxl I found out a better solution :) do not use GlobalConfiguration at all
151

See @gentiane's answer below for the correct way to handle this now.

At the end of the Application_Start method in Global.Asax.cs try adding:-

GlobalConfiguration.Configuration.EnsureInitialized(); 

3 Comments

I was getting this answer so I compared my project that was generated from a preview version of VS 2013 to one that was generated with Update 1 and it the difference is that they replaced WebApiConfig.Register(...) with GlobalConfiguration.Configure(...) as gentiane describes in their answer. This does resolve the issue.
That's exactly what GlobalConfiguration.Configure(Action<HttpConfiguration> configurationCallback) will call after the configurationCallback.
Error can also occur when the DI configuration is done before the GlobalConfiguration.Configure(WebApiConfig.Register); call
86

I actually got this error when I was using Attribute Routing within my WebApi.

I had

[Route("webapi/siteTypes/{siteTypeId"]

instead of

[Route("webapi/siteTypes/{siteTypeId}"]

for my route and got this error. I had simply missed out the closing curly bracket. Once I added it back in, this error didn't occur again.

10 Comments

I also had this problem when i prefixed the route with a slash [Route("/api/"]) instead of [Route("api")]
{int:id} instead of {id:int}
This one gets me all the time, but it used to give a different error. After upgrading to visual studio 2015 and .Net 4.6 I get this error.
My error was [Route("api/{parameter:string}")] instead of [Route("api/{parameter}")]. Apparently putting :string as type is wrong as it is the default.
Similar to Jamby, my error was that I needed: [Route("api/ObjectOfInterest/{type}/{name}")] ... but: [Route("api/ObjectOfInterest/{type:string}/{name:string}")] // WRONG ... was not working. I know it is weird that I need a parameter named 'Type' that is a string (and not a System.Type) ... but removed the string specification and it works fine.
|
34

This is old, but is the first result on google when searching for this error. After quite a bit of digging I was able to figure out what was going on.

tldr:
All GlobalConfiguration.Configure does is invoke your action and call EnsureInitialized(). config.MapAttributeRoutes() must be called before EnsureInitialized() since EnsureInitialized only runs once.

Meaning: if you're coming from an existing Mvc project, all you have to do is:

  1. Add GlobalConfiguration.Configuration.EnsureInitialized(); to the bottom of your Application_Start method.

OR

  1. Move your entire configuration into a single call to GlobalConfiguration.Configure:
GlobalConfiguration.Configure(config => { WebApiConfig.Register(config); config.MapAttributeRoutes(); ... }); 

Digging Deeper

HttpConfiguration.Configuration has an "Initializer" property defined like this:

public Action<HttpConfiguration> Initializer; 

HttpConfiguration.EnsureInitialized() runs this action and sets _initialized to true

public void EnsureInitialized() { if (_initialized) { return; } _initialized = true; Initializer(this); } 

HttpConfiguration.MapAttributeRoutes calls internal method AttributeRoutingMapper.MapAttributeRoutes which sets HttpConfiguration.Initializer

public static void MapAttributeRoutes(...) { RouteCollectionRoute aggregateRoute = new RouteCollectionRoute(); configuration.Routes.Add(AttributeRouteName, aggregateRoute); ... Action<HttpConfiguration> previousInitializer = configuration.Initializer; configuration.Initializer = config => { previousInitializer(config); ... }; } 

GlobalConfiguration.Configure runs EnsureInitialized immediately after invoking your action:

public static void Configure(Action<HttpConfiguration> configurationCallback) { if (configurationCallback == null) { throw new ArgumentNullException("configurationCallback"); } configurationCallback.Invoke(Configuration); Configuration.EnsureInitialized(); } 

Don't forget, if you run in to a wall, the source for asp.net is available at http://aspnetwebstack.codeplex.com/SourceControl/latest

2 Comments

The solution with single call to GlobalConfiguration.Configure saved my life. I had issues with attribute based routing and DI configuration together with the correct order of calling the configurations. I also uses MS ApiVersioning, where I needed the DI injections done before the first route hits the versioning attributes. Thx a lot
Is there a reason as to why the configuration isn't initialized after I explicitly called mapattributerouting?
12

I've had a related issue. Sometimes calling GlobalConfiguration.Configure multiple times triggers this error. As a workaround, I've put all configuration initialization logic in one place.

2 Comments

Yup, this was definitely the issue in my case
Same issue here! Been trying to fix the issue for a couple of hours, so the x for the comment.
11

IF THIS ERROR SEEMS TO HAVE COME "OUT OF NOWHERE", i.e. your app was working perfectly fine for a while, ask yourself: Did I add an action to a controller or change any routes prior to seeing this error?

If the answer is yes (and it probably is), you likely made a mistake in the process. Incorrect formatting, copy/pasting an action and forgetting to make sure the endpoint names are unique, etc. will all end you up here. The suggestion that this error makes on how to resolve it can send you barking up the wrong tree.

2 Comments

This exactly what happened to me. I changed a route but had left an erroneous curly brace on the end like this: [Route("GetStuff}")]
Out of all these answers, I feel like this is the only true answer. It's too vague to indicate exactly why this error is happening, but stepping backwards in endpoint or controller changes always fixes it for me.
8

Although the above answer works if incase that is not set, In my case this stuff was set already. What was different was that, for one of the APIs I had written, I had prefixed the route with a / . Example

[Route("/api/abc/{client}")] 

.Changing this to

[Route("api/abc/{client}")] 

fixed it for me

3 Comments

@Svend Indeed. Seemed like a stupid thing, but seems thats the issue in quite a few cases. :P
@The0bserver this worked for me as well. It was difficult to diagnose because at the top of my controller class I had an HttpPrefix decorator and then for my individual endpoint I had the decorator: [Route("/")]. By simply passing an empty String in the route fixed the issue.
Glad it helped. :)
7

For me, the problem was that I was trying to use named parameters for query string fields in my routes:

[Route("my-route?field={field}")] public void MyRoute([FromUri] string field) { } 

Query string fields are automatically mapped to parameters and aren't actually part of the route definition. This works:

[Route("my-route")] public void MyRoute([FromUri] string field) { } 

Comments

3

Call

GlobalConfiguration.Configuration.MapHttpAttributeRoutes(); 

before

GlobalConfiguration.Configure(c => ...); 

completes its execution.

Comments

2

I got this error when the version of Newtonsoft.Json was different in my main project compared to the helper project

1 Comment

Quick addition: make sure to clean your solution after fixing the reference issue and double check that the final deployed DLL is the correct version :)
1

One typically gets this exception when route templates in "Attribute Routing" are not proper.

For example, i got this when i wrote the following code:

[Route("{dirName:string}/contents")] //incorrect public HttpResponseMessage GetDirContents(string dirName) { ... } 

In route constraints syntax {parameter:constraint}, constraint by default is of type string. No need to mention it explicitly.

[Route("{dirName}/contents")] //correct public HttpResponseMessage GetDirContents(string dirName) { ... } 

Comments

0

I began getting this error one day. After I'd altered our app to call EnsureInitialized() I was able to see the root cause.

I had a custom attribute, a filter, on an action. That attribute class had had a breaking change made in the NuGet package in which it lives.

Even though I'd updated the the code and it all compiled, the local IIS worker was loading an old DLL and not finding a class member during initialization, reading attributes on actions etc.

For some reason (possibly due to order/when our logging is initialized), this error was not discoverable, possibly leaving the WebAPI in a strange state, until I'd added EnsureInitialized() which caught the exception and surfaced it.

Performing a proper bin and obj clean via a handy script resolved it.

Comments

0

In my case I created the webservice in project A and started it from Project B and I got exactly this error. The problem was that some .dll-files which are required by A where missing in the build-output-folder of B. Ensure that these .dll-files are available fixed it.

Comments

0

In my case , i used an Entity as parameter of my action that its 'Schema' is missing.

Wrong attribute:

[Table("Table name", Schema = "")] 

Correct :

[Table("Table name", Schema = "schema name")] 

Comments

0

In my case I fixed replacing:

<Route("{id:string}")> 

with

<Route("{id}")> 

Strange that I was sure that the original code was working before suddenly stopping, go figure....

Comments

0

I experienced this similar error.

<Error> <Message>An error has occurred.</Message> <ExceptionMessage>The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.</ExceptionMessage> <ExceptionType>System.InvalidOperationException</ExceptionType> <StackTrace> at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)</StackTrace> </Error> 

After fiddling with it for a while, I realized two problems: directory name collides with routing prefix and routing prefix must not end with '/'. When starting up the service for debugging I got this browser error after adding the SampleController.cs.

The folder structure

 /api/Controllers/SampleController.cs /api/Model/... 

SampleController.cs

[RoutePrefix("api/sub/{parameterId}/more/")] public class SampleController : ApiController { [HttpGet] [Route("")] public IHttpActionResult Get(int parameterId) { return Ok("Knock Knock..."); } } 

Changing the routing prefix to not end in '/' and not colliding with the directory name solved the problem.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.