【问题标题】:ASP.NET Web API: calling ApiDescriptions on a ApiExplorer throws: This method cannot be called during the application's pre-start initialization phaseASP.NET Web API:在 ApiExplorer 上调用 ApiDescriptions 抛出:在应用程序的预启动初始化阶段无法调用此方法
【发布时间】:2012-09-06 11:08:43
【问题描述】:

根据这篇博文http://codebetter.com/johnvpetersen/2012/08/01/documenting-your-asp-net-web-apis/,我正在编写一个“文档控制器”,与上面的链接中所做的差不多。但是,当我拨打以下电话时

GlobalConfiguration.Configuration.Services.GetApiExplorer().ApiDescriptions

我收到 InvalidOperationException 声明:“在应用程序的预启动初始化阶段无法调用此方法。”。我看过ASP.NET: This method cannot be called during the application's pre-start initialization stage 但这并没有为我解决问题。我使用的是 ASP.NET Web API 4.20710.0,根据 NuGet 最新版本(是吗?)。

有人愿意就这个问题向我提供一些帮助吗?是f.ex吗?可以在调用 ApiDescriptions 之前强制完成预启动初始化阶段吗?还是可以换一种方式?

感谢您的任何意见!

编辑

调用是在 GET 中进行的

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

上面的链接提供了一个完整的例子。

【问题讨论】:

  • 你在哪里有这条线GlobalConfiguration.Configuration.Services.GetApiExplorer().ApiDescriptions?哪个类哪个方法?

标签: asp.net asp.net-mvc asp.net-web-api asp.net-mvc-apiexplorer


【解决方案1】:

我意识到,在对 System.Web.Http 程序集进行反编译后,最可能的原因是 ApiExplorers 内部集合 Lazy&lt;Collection&lt;ApiDescription&gt;&gt; 没有正确初始化,原因我不知道或已设置为不可访问状态,导致异常。我通过更新ApiExplorer 解决了这个问题。在我的ApiController

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

    ...
} 

【讨论】:

  • 这行得通!但有一个细节。如果我将ApiExplorer 创建为ApiExplorer(GlobalConfiguration.Configuration),那么我仍然会得到InvalidOperationException,但ApiExplorer(ControllerContext.Configuration) 工作正常。
猜你喜欢
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
  • 2021-03-20
  • 2014-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-12
相关资源
最近更新 更多