2014-12-02 57 views
4

我想使用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用於外部項目或程序集的Api Explorer

但是,這個項目有點過時了,不適用於當前的web api。 我想擁有:

  1. 一個控制檯程序,其中安裝了api explorer核心庫。
  2. 它從另一個項目中獲取一個程序集,並運行Api Explorer以獲取所有REST路徑和方法。
  3. 我不希望Api Explorer或幫助頁面安裝在我定位的項目上。我只想使用該項目的組件,並且控制檯應用程序將具有所有必需的API Explorer軟件包。

這可能嗎?

我可以加載程序集並運行Api Explorer嗎?

+0

我有同樣的問題。你找到解決方案嗎? – fra 2016-11-01 06:14:37

+0

嗨,我最接近的是安裝以下Nuget包並啓用XML文檔生成:https://www.nuget.org/packages/Microsoft.AspNet.WebApi.HelpPage/ – Ramin 2016-11-01 17:55:31

+0

謝謝Ramin。爲了我的需要,我需要實際的swagger文件 – fra 2016-11-01 19:22:35

回答

0

此代碼適用於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); 

哪裏Startup是項目的啓動類。這裏的項目直接引用,但你應該能夠加載程序集並相應地使用它。

相關問題