IT

HttpConfiguration.EnsureInitialized ()를 확인하십시오

lottoking 2020. 6. 21. 19:13
반응형

HttpConfiguration.EnsureInitialized ()를 확인하십시오


Visual Studio 2013을 설치했으며 앱을 실행할 때 아래 오류가 발생합니다.

이 객체를 어디에서 초기화해야하는지 전혀 모른다.

무엇을해야합니까?

    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

이것은 AlumCloud입니다


이것을 처리하는 올바른 방법은 아래 @ gentiane의 답변을 참조하십시오 .

Application_Start방법 의 끝에 다음을 Global.Asax.cs추가하십시오.

GlobalConfiguration.Configuration.EnsureInitialized(); 

Application_Start의 끝에서이를 수행하면 WebApiConfig.Register가 호출되었으므로 너무 늦습니다.

이를 해결하는 가장 좋은 방법은 Global.asax에서 대체하여 새로운 초기화 방법을 사용하는 것입니다.

WebApiConfig.Register(GlobalConfiguration.Configuration);

으로

GlobalConfiguration.Configure(WebApiConfig.Register);

WebApi 내에서 속성 라우팅을 사용할 때 실제로이 오류가 발생했습니다.

나는했다

[라우트 ( "webapi / siteTypes / {siteTypeId"]

대신에

[라우트 ( "webapi / siteTypes / {siteTypeId}"]

내 경로에 대한이 오류가 발생했습니다. 나는 닫는 중괄호를 놓쳤다. 다시 추가하면이 오류가 다시 발생하지 않습니다.


이것은 오래되었지만이 오류를 검색 할 때 Google의 첫 번째 결과입니다. 약간의 파고 난 후에 나는 무슨 일이 있었는지 알아낼 수있었습니다.

tldr :
모든 GlobalConfiguration.Configure 가 수행하는 것은 조치를 호출하고 VerifyInitialized ()를 호출하는 입니다. VerifyInitialized 는 한 번만 실행되므로 Config.MapAttributeRoutes ()는 VerifyInitialized () 전에 호출해야합니다 .

의미 : 기존 Mvc 프로젝트에서 오는 경우 다음을 수행하면됩니다.

  1. GlobalConfiguration.Configuration.EnsureInitialized ();를 추가하십시오 . Application_Start 메소드 의 맨 아래에 .

또는

  1. 전체 구성을 GlobalConfiguration.Configure 에 대한 단일 호출로 이동하십시오 .

GlobalConfiguration.Configure(config => 
{
    WebApiConfig.Register(config);
    config.MapAttributeRoutes();
    ...
});

더 깊이 파기

HttpConfiguration.Configuration 에는 다음과 같이 정의 된 "Initializer"속성이 있습니다.

public Action<HttpConfiguration> Initializer;

HttpConfiguration.EnsureInitialized () 는이 동작을 실행하고 _initializedtrue로 설정 합니다.

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

HttpConfiguration.MapAttributeRoutesHttpConfiguration.Initializer 를 설정하는 내부 메소드 AttributeRoutingMapper.MapAttributeRoutes호출 합니다 .

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


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.


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

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


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.


Call

GlobalConfiguration.Configuration.MapHttpAttributeRoutes();

before

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

completes its execution.


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


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

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.


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.

참고URL : https://stackoverflow.com/questions/19969228/ensure-that-httpconfiguration-ensureinitialized

반응형