用于外部项目或程序集的Api Explorer

Ram*_*min 5 c# asp.net-mvc asp.net-web-api

我想使用Web API的Api Explorer来开始生成自己的文档html页面。我要针对的是此处描述的内容:http : //blogs.msdn.com/b/yaohuang1/archive/2013/01/20/design-time-generation-of-help-page-or- asp-net-web-api.aspx代理

但是,该项目有些过时了,不能与当前的Web api一起使用。我希望有:

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

这可能吗?

我可以加载程序集并在其上运行Api Explorer吗?

Jor*_*eda 1

此代码适用于 ASP.NET Core 2.0,但可能对您有用。它依赖于Swashbuckle.AspNetCoreMicrosoft.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);
Run Code Online (Sandbox Code Playgroud)

Startup您的项目的 Startup 类在哪里。这里直接引用项目,但您应该能够加载程序集并相应地使用它。