用于外部项目或程序集的 API 资源管理器

本文关键字:API 资源管理器 程序集 外部 项目 用于 | 更新日期: 2023-09-27 18:33:02

我想使用Web API的Api Explorer来开始生成我自己的文档html页面。我试图瞄准的是这里描述的内容:http://blogs.msdn.com/b/yaohuang1/archive/2013/01/20/design-time-generation-of-help-page-or-proxy-for-asp-net-web-api.aspx

但是,这个项目有点过时,不适用于当前的 Web API。我想要:

  1. 安装了 api 资源管理器核心库的控制台程序。
  2. 它从另一个项目接收程序集,并在其上运行 API 资源管理器以获取所有 REST 路径和方法。
  3. 不希望在我的目标项目中安装 Api 资源管理器或帮助页面。我只想使用项目的程序集,控制台应用程序将拥有所有必要的 API 资源管理器包。

这可能吗?

是否可以加载程序集并在其上运行 API 资源管理器?

用于外部项目或程序集的 API 资源管理器

此代码适用于 ASP.NET Core 2.0,但它可能对您有用。它依赖于Swashbuckle.AspNetCore和Microsoft.AspNetCore.TestHost:

IWebHostBuilder builder = new WebHostBuilder()
    .UseStartup<Startup>()
    .ConfigureServices(services =>
    {
        services.AddSwaggerGen(opts =>
        {
            opts.SwaggerDoc("doc-name", new Info { Title = "Title", Version = "v1" });
        });
    });
JsonSerializerSettings mvcSerializerSettings;
SwaggerDocument document;
using (var testServer = new TestServer(builder))
{
    IOptions<MvcJsonOptions> mvcOptions = testServer.Host.Services.GetService<IOptions<MvcJsonOptions>>();
    mvcSerializerSettings = mvcOptions.Value.SerializerSettings;
    ISwaggerProvider swaggerProvider = testServer.Host.Services.GetService<ISwaggerProvider>();
    document = swaggerProvider.GetSwagger("doc-name");
}
// Reference: Swashbuckle.AspNetCore.Swagger/Application/SwaggerSerializerFactory.cs
var settings = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore,
    Formatting = mvcSerializerSettings.Formatting,
    ContractResolver = new SwaggerContractResolver(mvcSerializerSettings),
};
string json = JsonConvert.SerializeObject(document, settings);

其中Startup是项目的启动类。此处直接引用项目,但您应该能够加载程序集并相应地使用它。

这受到

虚张声势的样本的启发,但也只能使用 ApiExplorer .

您可以创建 OWIN TestServer ,创建HttpConfiguration,运行 WebApi OWIN 初始化代码,然后从初始化的HttpConfiguration创建ApiExplorer。您可能遇到的唯一问题是在目标程序集中查找启动代码的 WebApi 部分。就我而言,我在同一解决方案中引用了WebAPi项目,因此调用相关的启动代码更容易。

private static Collection<ApiDescription> GetApiDescriptions()
{
  Collection<ApiDescription> descriptions = null;
  TestServer.Create(app => {
    var httpConfiguration = new HttpConfiguration();
    // This is the call to my webapi startup method in the target project, this may be tricky to find (using reflection) in your case
    new Startup().ConfigureWebApi(app, httpConfiguration);
    var apiExplorer = new ApiExplorer(httpConfiguration);
    httpConfiguration.EnsureInitialized();
    descriptions = apiExplorer.ApiDescriptions;
  });
  return descriptions;
}