C# 确保 HttpConfiguration.EnsureInitialized()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19969228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:15:50  来源:igfitidea点击:

Ensure that HttpConfiguration.EnsureInitialized()

c#.netasp.net-mvc-routing

提问by Filling The Stack is What I DO

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

我已经安装了 Visual Studio 2013,当我运行我的应用程序时,出现以下错误。

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

这是给AlumCloud 的

采纳答案by Ian Mercer

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

请参阅下面@gentiane 的回答,了解现在处理此问题的正确方法。

At the end of the Application_Startmethod in Global.Asax.cstry adding:-

在尝试添加Application_Start方法的末尾Global.Asax.cs:-

GlobalConfiguration.Configuration.EnsureInitialized(); 

回答by gentiane

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

如果您在 Application_Start 结束时执行此操作,则为时已晚,因为 WebApiConfig.Register 已被调用。

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

解决此问题的最佳方法是通过替换 Global.asax 使用新的初始化方法:

WebApiConfig.Register(GlobalConfiguration.Configuration);

by

经过

GlobalConfiguration.Configure(WebApiConfig.Register);

回答by Gleno

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

我有一个相关的问题。有时GlobalConfiguration.Configure多次调用会触发此错误。作为一种解决方法,我已将所有配置初始化逻辑放在一个地方。

回答by abatishchev

Call

称呼

GlobalConfiguration.Configuration.MapHttpAttributeRoutes();

before

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

completes its execution.

完成其执行。

回答by Jeff Yates

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

当我在 WebApi 中使用属性路由时,我实际上遇到了这个错误。

I had

我有

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

[路由(“webapi/siteTypes/{siteTypeId”]

instead of

代替

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

[路由(“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.

对于我的路线并收到此错误。我只是错过了结束大括号。一旦我重新添加它,这个错误就不再发生了。

回答by NathanAldenSr

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

回答by tField

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.

这是旧的,但这是搜索此错误时在 google 上的第一个结果。经过一番挖掘,我能够弄清楚发生了什么。

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

tldr:
所有GlobalConfiguration.Configure所做的就是调用您的操作并调用ensureInitialized()config.MapAttributeRoutes()必须在EnsureInitialized()之前调用,因为EnsureInitialized 只运行一次。

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

意思是:如果你来自一个现有的 Mvc 项目,你所要做的就是:

  1. Add GlobalConfiguration.Configuration.EnsureInitialized();to the bottom of your Application_Startmethod.
  1. 添加 GlobalConfiguration.Configuration.EnsureInitialized(); Application_Start方法的底部。

OR

或者

  1. Move your entire configuration into a single call to GlobalConfiguration.Configure:
  1. 将您的整个配置移动到对GlobalConfiguration.Configure的单个调用中:
GlobalConfiguration.Configure(config => 
{
    WebApiConfig.Register(config);
    config.MapAttributeRoutes();
    ...
});


Digging Deeper

深层发掘

HttpConfiguration.Configurationhas an "Initializer" property defined like this:

HttpConfiguration.Configuration有一个“Initializer”属性,定义如下:

public Action<HttpConfiguration> Initializer;

HttpConfiguration.EnsureInitialized()runs this action and sets _initializedto true

HttpConfiguration.EnsureInitialized()运行此操作并将_initialized设置为true

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

HttpConfiguration.MapAttributeRoutescalls internal method AttributeRoutingMapper.MapAttributeRouteswhich sets HttpConfiguration.Initializer

HttpConfiguration.MapAttributeRoutes调用内部方法AttributeRoutingMapper.MapAttributeRoutes来设置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.Configureruns EnsureInitializedimmediately after invoking your action:

GlobalConfiguration.Configure在调用您的操作后立即运行确保初始化

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

不要忘记,如果你碰壁了,可以在http://aspnetwebstack.codeplex.com/SourceControl/latest找到 asp.net 的源代码

回答by Luke Puplett

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

有一天我开始收到这个错误。在我将我们的应用程序更改为调用后,EnsureInitialized()我能够看到根本原因。

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.

我有一个自定义属性,一个过滤器,一个动作。该属性类在它所在的 NuGet 包中进行了重大更改。

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.

即使我更新了代码并编译了所有代码,本地 IIS 工作人员正在加载一个旧的 DLL,并且在初始化、读取操作属性等期间没有找到类成员。

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.

出于某种原因(可能是由于顺序/我们的日志记录初始化时),无法发现此错误,可能会使 WebAPI 处于一种奇怪的状态,直到我添加了EnsureInitialized()它来捕获异常并将其浮出水面。

Performing a proper binand objclean via a handy script resolved it.

通过一个方便的脚本执行正确binobj干净的解决了它。

回答by David Lilljegren

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

当我的主项目中的 Newtonsoft.Json 版本与辅助项目不同时,我收到此错误

回答by Tarun Kumar

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.

在路由约束语法 {parameter:constraint} 中,约束默认为string类型。无需明确提及。

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