160

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

16 Answers16

255

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);
gentiane
  • 6,715
  • 3
  • 23
  • 34
  • 13
    Based on Microsoft documentation this should be the right way to do it. http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#constraints – Dalorzo Feb 06 '14 at 20:16
  • I've been migrating an mvc app, when the api routes weren't working, adding this and MapHttpAttributeRoutes brought it all to life. – Phil Cooper Mar 22 '14 at 08:16
  • But what in case if u have WebApiConfig non-static class? – Georgy Grigoryev Jan 30 '17 at 14:15
  • @GeorgyGrigoryev : you can just instantiate it inside the action like so: `GlobalConfiguration.Configure(config => new WebApiConfig().Register(config));` – cmxl Jun 01 '17 at 12:30
  • @cmxl I found out a better solution :) do not use GlobalConfiguration at all – Georgy Grigoryev Jun 03 '17 at 14:22
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(); 
Korayem
  • 12,108
  • 5
  • 69
  • 56
Ian Mercer
  • 38,490
  • 8
  • 97
  • 133
  • 3
    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. – Bryan Bedard Feb 16 '14 at 16:10
  • 1
    That's exactly what `GlobalConfiguration.Configure(Action configurationCallback)` will call after the configurationCallback. – cmxl Jun 01 '17 at 12:36
  • 4
    Error can also occur when the DI configuration is done before the GlobalConfiguration.Configure(WebApiConfig.Register); call – Silvos Jul 03 '17 at 09:05
  • Thank you. That's been a thorn in my side. – Robert Bolton Mar 07 '18 at 18:30
82

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.

Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50
Jeff Yates
  • 1,053
  • 1
  • 10
  • 14
  • 27
    I also had this problem when i prefixed the route with a slash [Route("/api/"]) instead of [Route("api")] – cguedel May 21 '15 at 11:35
  • 2
    {int:id} instead of {id:int} – Marat Batalandabad Jun 29 '15 at 12:27
  • 1
    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. – nbering Aug 05 '15 at 14:47
  • 8
    My error was [Route("api/{parameter:string}")] instead of [Route("api/{parameter}")]. Apparently putting :string as type is wrong as it is the default. – Jamby May 25 '16 at 13:32
  • 1
    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. – Aidanapword Feb 16 '17 at 11:02
  • This saved me SO much time. – Mark Vickery Jan 26 '18 at 16:09
  • This was the issue for me as well. – Mitch Jan 30 '18 at 15:50
  • Wow, I had a stray '}' that I didn't notice that was causing this error. – jhunter Oct 19 '18 at 13:57
  • @cguedel nice - I had a trailing / on my RoutePrefix. No way they could easily validate these things, right? – Rob Grant Apr 10 '19 at 22:00
  • {id: int} instead of {id:int} was the issue for me – Érica Betto Sene Mar 23 '22 at 11:37
33

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

brenners1302
  • 1,440
  • 10
  • 18
tField
  • 390
  • 4
  • 4
  • 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 – Silvos Jan 09 '18 at 10:02
  • Is there a reason as to why the configuration isn't initialized after I explicitly called mapattributerouting? – Andes Lam Aug 27 '21 at 07:51
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.

Gleno
  • 16,621
  • 12
  • 64
  • 85
10

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.

Byron Jones
  • 702
  • 5
  • 11
  • This exactly what happened to me. I changed a route but had left an erroneous curly brace on the end like this: [Route("GetStuff}")] – Stu Price Feb 21 '20 at 20:43
  • 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. – Rudy Scoggins Apr 06 '23 at 19:50
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)
{
}
NathanAldenSr
  • 7,841
  • 4
  • 40
  • 51
7

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

The 0bserver
  • 826
  • 9
  • 18
  • @Svend Indeed. Seemed like a stupid thing, but seems thats the issue in quite a few cases. :P – The 0bserver Sep 22 '17 at 06:30
  • @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. – David Sep 18 '19 at 13:49
  • 1
    Glad it helped. :) – The 0bserver Sep 18 '19 at 14:31
3

Call

GlobalConfiguration.Configuration.MapHttpAttributeRoutes();

before

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

completes its execution.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
2

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

David Lilljegren
  • 1,799
  • 16
  • 19
  • 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 :) – Marcel Gruber Jun 06 '18 at 15:10
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) { ... }
Tarun Kumar
  • 729
  • 1
  • 8
  • 16
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.

Luke Puplett
  • 42,091
  • 47
  • 181
  • 266
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.

anion
  • 1,516
  • 1
  • 21
  • 35
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")]
Reza Nafisi
  • 1
  • 1
  • 2
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....

rsc
  • 10,348
  • 5
  • 39
  • 36
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.