Ensure that HttpConfiguration.EnsureInitialized()

C#.Netasp.net Mvc-Routing

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

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

> 2. 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

Solution 5 - C#

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.

Solution 6 - C#

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

Solution 7 - C#

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

Solution 8 - C#

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.

Solution 9 - C#

Call

GlobalConfiguration.Configuration.MapHttpAttributeRoutes();

before

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

completes its execution.

Solution 10 - C#

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

Solution 11 - C#

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) { ... }

Solution 12 - C#

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.

Solution 13 - C#

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.

Solution 14 - C#

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")]

Solution 15 - C#

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....

Solution 16 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFilling The Stack is What I DOView Question on Stackoverflow
Solution 1 - C#gentianeView Answer on Stackoverflow
Solution 2 - C#Ian MercerView Answer on Stackoverflow
Solution 3 - C#Jeff YatesView Answer on Stackoverflow
Solution 4 - C#tFieldView Answer on Stackoverflow
Solution 5 - C#GlenoView Answer on Stackoverflow
Solution 6 - C#NathanAldenSrView Answer on Stackoverflow
Solution 7 - C#The 0bserverView Answer on Stackoverflow
Solution 8 - C#Byron JonesView Answer on Stackoverflow
Solution 9 - C#abatishchevView Answer on Stackoverflow
Solution 10 - C#David LilljegrenView Answer on Stackoverflow
Solution 11 - C#Tarun KumarView Answer on Stackoverflow
Solution 12 - C#Luke PuplettView Answer on Stackoverflow
Solution 13 - C#anionView Answer on Stackoverflow
Solution 14 - C#Reza NafisiView Answer on Stackoverflow
Solution 15 - C#rscView Answer on Stackoverflow
Solution 16 - C#Morten Gorm MadsenView Answer on Stackoverflow