我想使用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。 我希望:
这可能吗?
我可以加载程序集并在其上运行Api资源管理器吗?
答案 0 :(得分:0)
此代码适用于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
是您项目的Startup类。这里直接引用了项目,但您应该能够加载程序集并相应地使用它。
答案 1 :(得分:0)
这受swashbuckle sample的启发,但也可能仅使用ApiExplorer
。
您可以创建OWIN TestServer
,创建HttpConfiguration
,运行WebApi OWIN初始化代码,然后从初始化的ApiExplorer
创建HttpConfiguration
。您可能唯一的问题是在目标程序集中找到启动代码的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;
}