2017-05-07 136 views
1

我在WebAPI項目中設置了Swagger/Swashbuckle。我遵循guide from Microsoft,其中介紹瞭如何使用Swagger設置Aspnet.WebApi.Versioning。我的API有多個版本,所以有{version}參數在路由屬性設置,如下所示:如何向SwaggerUi中顯示的路徑提供路徑參數?

[ApiVersion("2")] 
[RoutePrefix("api/{version:apiVersion}/values")] 
public class AccountController : ApiController 
{ 
    [Route("UserInfo")] 
    public IEnumerable<string> Get() 
    { 
     return new string[] { "value1", "value2" }; 
    } 
} 

我的問題是,這顯示在文檔中所示的路徑{version}屬性,像這樣:

enter image description here

相反,我想這條道路屬性確實有在ApiVersion屬性的值,因此有可能是誰閱讀文檔的用戶不會混淆。理想的情況下,考慮到UrlDiscoverySelector設置爲v2以上的路徑應該是:

/api/2/account/userinfo 
/api/2/account/externallogin 
/api/2/account/manageinfo 

我試圖簡單地在該ApiExplorerRelativePath在UI工作更換{version},但打破了測試功能{version}改變到query參數而不是path,這不是我的API配置。

是否可以在swagger構建文檔之前修改ApiExplorer中的值,同時仍保留測試功能?

回答

0

我使用的是Swashbuckle和使用文檔過濾器

public class VersionedOperationsFilter : IDocumentFilter 
{ 
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) 
    { 
     foreach (var apiDescriptionsGroup in context.ApiDescriptionsGroups.Items) 
     { 
      var version = apiDescriptionsGroup.GroupName; 
      foreach (ApiDescription apiDescription in apiDescriptionsGroup.Items) 
      { 
       apiDescription.RelativePath = apiDescription.RelativePath.Replace("{version}", version); 
      } 
     } 
    } 
} 

,並在Startup.cs ConfigureServices方法中添加此過濾器:

services.AddMvc(); 
     var defaultApiVer = new ApiVersion(1, 0); 


     services.AddApiVersioning(option => 
     { 
      option.ReportApiVersions = true; 
      option.AssumeDefaultVersionWhenUnspecified = true; 
      option.DefaultApiVersion = defaultApiVer; 
     }); 

     services.AddMvcCore().AddVersionedApiExplorer(e=>e.DefaultApiVersion = defaultApiVer); 

     services.AddSwaggerGen(
      options => 
      { 
       var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>(); 
       options.DocumentFilter<VersionedOperationsFilter>(); 

       //// add a swagger document for each discovered API version 
       //// note: you might choose to skip or document deprecated API versions differently 
       foreach (var description in provider.ApiVersionDescriptions) 
       { 
         options.SwaggerDoc(description.GroupName.ToString(), 
          CreateInfoForApiVersion(description)); 
       } 

       //// integrate xml comments 
       options.IncludeXmlComments(Path.ChangeExtension(Assembly.GetEntryAssembly().Location, "xml")); 

      }); 

end result in Swagger UI

+0

感謝您的回覆,並對遲到的反應表示歉意,因爲我只是想再次看到這一點。你的代碼看起來很理想,但是你用於'IDocumentFilter'的簽名與我使用的Seashbuckle版本不匹配。它反而期望'應用(SwaggerDocument swaggerDoc,SchemaRegistry schemaRegistry,IApiExplorer apiExplorer)' - 請注意,我正在開發一個WebApi項目,而不是一個MVC項目,如果它有所作爲 –

+0

問題是我正在使用Swashbuckle.AspNetCore版本,所以它有一個不同的簽名,但原則應該是相同的 - 像[這裏](https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Dummy.Core/SwaggerExtensions/AppendVersionToBasePath.cs#L14) –