希望有人尝试过与MVC 6和Swagger中的版本化API类似的东西,以显示有关不同版本的文档.
我在这个ASP.NET 5存储库中使用MVC 6中推荐的API版本.我所做的唯一改变是GetVersion方法从请求的自定义http头读取api版本:
//in VersionRangeValidator.cs public static string GetVersion(HttpRequest request) { //return request.Query["version"]; if (!string.IsNullOrWhiteSpace(request.Headers[Constants.CommonRoutingDefinitions.ApiVersionSegmentName])) { return request.Headers[Constants.CommonRoutingDefinitions.ApiVersionSegmentName]; } return Constants.CommonRoutingDefinitions.CurrentApiVersion; }
我有一个像这样的控制器:
[Route("api/[controller]")] [Produces(Constants.MediaTypeNames.ApplicationJson)] public class TagsController : Controller { private readonly ITagService _tagService; public TagsController(ITagService tagService) { _tagService = tagService; } ////// Version 1 by default /// ///All the tags [HttpGet] [Produces(typeof(IEnumerable))] public IEnumerable GetTags() { IEnumerable tags = _tagService.GetTags(); return tags; } /// /// Version 2 /// ///All the tags V2 [VersionGet("", versionRange: "[2]")] public IEnumerableGetTagsV2() { IList tags = new List { new Tag { Id = 1, Links = Enumerable.Empty().ToList(), Name = "Tag version 2" } }; return tags; } }
使用自定义http标头进行版本控制即可
GET/api /标签
Content-Type:application/json
默认情况下将触发GetTags()操作,因为没有指定标头和
GET/api /标签
api-version:2
Content-Type:application/json
将点击GetTagsV2()动作.
我已按照此博客中的步骤添加了Swagger UI和Swagger GEN库,因此在我的project.json
以下依赖项:
"Swashbuckle.SwaggerGen": "6.0.0-rc1-final", "Swashbuckle.SwaggerUi": "6.0.0-rc1-final"
然后在我的Startup.cs中,我将Swagger添加到管道中
//inside Configure(IApplicationBuilder app) app.UseSwaggerGen(); app.UseSwaggerUi();
我按如下方式配置Swagger:
private void ConfigureSwagger(IServiceCollection services) { services.AddSwaggerGen(); services.ConfigureSwaggerDocument(options => { options.MultipleApiVersions(new Swashbuckle.SwaggerGen.Info[] { new Swashbuckle.SwaggerGen.Info { Version = "v1", Title = "MyApp API", Description = "A RESTful API" }, new Swashbuckle.SwaggerGen.Info { Version = "v2", Title = "MyApp API (v2)", Description = "A RESTful API" } }, (description, version) => { //description is an instance of ApiDescription and //version is either "v1" or "v2" //depending on the user choice in swagger UI page //TODO, how can I know whether the action belongs to v1 or to v2 to return true or false as appropriate? }); options.OperationFilter(new Swashbuckle.SwaggerGen.XmlComments.ApplyXmlActionComments(Configuration["Documentation:SwaggerDocXml"])); }); services.ConfigureSwaggerSchema(options => { options.DescribeAllEnumsAsStrings = true; options.ModelFilter(new Swashbuckle.SwaggerGen.XmlComments.ApplyXmlTypeComments(Configuration["Documentation:SwaggerDocXml"])); }); }
问题是我不知道如何从描述(这是Microsoft.AspNet.Mvc.ApiExplorer.ApiDescription的一个实例)获得必要的信息,以了解是否必须在Swagger UI中显示给定的操作或不依赖在指定的版本上.任何提示将不胜感激.这将有助于理解这个用于版本控制的ASP.NET 5存储库实现是如何工作的,因为我仍然不能很好地理解它,并且无法找到关于动作约束如何工作的良好解释.
PS:这个stackoverflow问题帮助我实现了MVC 6的版本控制,但我找不到很多关于Swagger如何与这种版本化API的方式集成.