ASP.NET Web API: calling ApiDescriptions on a ApiExplorer throws: This method cannot be called during the application's pre-start initialization phase

StackOverflow https://stackoverflow.com/questions/12298752

Question

Based on this blogpost http://codebetter.com/johnvpetersen/2012/08/01/documenting-your-asp-net-web-apis/ I'm writing a "documentation-controller", pretty much as it's done in the above link. However when I make the following call

GlobalConfiguration.Configuration.Services.GetApiExplorer().ApiDescriptions

I get a InvalidOperationException stating: "This method cannot be called during the application's pre-start initialization phase.". I've had a look at ASP.NET: This method cannot be called during the application's pre-start initialization stage but that didn't solve it for me. I'm on ASP.NET Web API 4.20710.0, which is the latest according to NuGet (yes?).

Anyone care to provide me with some help on the issue? Is it f.ex. possible to force the pre-start initialization phase to finish before I make the call to ApiDescriptions? Or can it perhaps be tweeked another way?

Thanks for any input!

EDIT

The call is made from within a GET

public List<APIEndPoint> Get()
{
  var controllers = GlobalConfiguration
    .Configuration
    .Services
    .GetApiExplorer()
    .ApiDescriptions; 
  ... 
}

The above link provides a full example.

Was it helpful?

Solution

I realised, after decopiling the System.Web.Http assembly, that there the most probable cause to this was the ApiExplorers inner collection Lazy<Collection<ApiDescription>> that had, for reasons I dont't know, not been properly initialized or had been set in an inaccessibale state, causing the exception. I solved the issue by newing up a ApiExplorer. In my ApiController:

public List<APIEndPoint> Get()
{
    var apiEx = new ApiExplorer(ControllerContext.Configuration);
    var controllers = apiEx.ApiDescriptions;

    ...
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top