首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在单个控制器上支持api版本上生成的Swagger文档的问题

在单个控制器上支持api版本上生成的Swagger文档的问题
EN

Stack Overflow用户
提问于 2017-06-27 08:07:40
回答 1查看 2.4K关注 0票数 1

我有两个Swagger文档,分别是docs/v1和docs/v2。但是,docs/v2没有提供有关动作GetV2()的信息。如果斯瓦什巴克尔有解决这一问题的选项,请帮助。

1.由于路由模板似乎与get()和getv2()操作相同,所以docs v2没有显示任何关于getV2().的信息。

2. Swagger定义在docs/v1中以v{version}/get的形式出现时,不显示v1.0/get

注意:我已经参考了像素控制示例,但不确定我遗漏了什么。所有示例都引用了Swashbuckle.core,而我使用的是Swashbuckle。

代码语言:javascript
复制
[ApiVersion("1.0")] 
[ApiVersion("2.0")]
public class HelloController : ApiControllerBase
{
    [MapToApiVersion("1.0")]
    [Route("v{version:apiVersion}/get")]
    [HttpGet]
    public ProjectSightActionResult Get()
    {
        return new Ok("Version 1.0");
    }

    [MapToApiVersion("2.0")]
    [Route("v{version:apiVersion}/get")]
    [HttpGet]
    public ProjectSightActionResult GetV2()
    {
        return new Ok("Version 2.0");
    }
}

这是我的控制器,包括两个操作,一个用于版本v1,一个用于v2。下面是路由约束的webapi.config:

代码语言:javascript
复制
public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Version Start 
    // https://github.com/Microsoft/aspnet-api-versioning/wiki/Versioning-via-the-URL-Path
    // added to the web api configuration in the application setup
    var constraintResolver = new DefaultInlineConstraintResolver()
    {
        ConstraintMap = {["apiVersion"] = typeof( ApiVersionRouteConstraint )}
    };

    config.MapHttpAttributeRoutes(constraintResolver);
    config.AddApiVersioning();
    // Version End 

    // Web API routes
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    config.Filters.Add(new AuthenticationFilter());


    // This causes Web API to remove the IPrincipal from any request that enters the Web API pipeline. Effectively, it "un-authenticates" the request. 
    // https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/authentication-filters
    config.SuppressHostPrincipal();
}

我的Swagger配置有以下代码:

代码语言:javascript
复制
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
namespace sample.WebAPI
{
    public class SwaggerConfig
    {
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

             GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {
                    c.MultipleApiVersions(
                        (apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion),
                               vc =>
                                 {
                                     vc.Version("v1", "sample.WebAPI");
                                     vc.Version("v2", "sample.WebAPI");
                                 });
                    }
                )
                .EnableSwaggerUi(c =>
                    {            
                        c.EnableDiscoveryUrlSelector();

                       // If your API supports ApiKey, you can override the default values.
                       // "apiKeyIn" can either be "query" or "header"                                                

                        c.EnableApiKeySupport("x-jwt-assertion", "header");
                      });
        }

        private static string GetXmlCommentsPath()
        {
            return string.Format(@"{0}\bin\XmlComments.xml", AppDomain.CurrentDomain.BaseDirectory);
        } 

        private static bool ResolveVersionSupportByRouteConstraint(ApiDescription apiDesc, string targetApiVersion)
        {
            //check for deprecated versions
            var controllerVersionAttributes = apiDesc.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<ApiVersionAttribute>(true);
            if (!controllerVersionAttributes.Any())
            {
                return true; // include when no attributes are defined
            }

            if (targetApiVersion.StartsWith("v"))
            {
                targetApiVersion = targetApiVersion.Substring(1); // remove the leading "v" in `v{x.x}`
            }

            var apiVersion = ApiVersion.Parse(targetApiVersion);

            var controllerApiVersion = controllerVersionAttributes
                .Where(x => x.Versions.Contains(apiVersion))
                .FirstOrDefault();

            // has a compatible version, now check the action for [MapToApiVersion]
            if (controllerApiVersion != null)
            {
                var actionMapToAttributes = apiDesc.ActionDescriptor.GetCustomAttributes<MapToApiVersionAttribute>(false);
                if (!actionMapToAttributes.Any())
                {
                    return true; // no MapTo attributes matched, then include the action
                }

                if (actionMapToAttributes.Any(x => x.Versions.Contains(apiVersion)))
                {
                    return true; // include mapped action
                }
            }

            return false;
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-03-26 02:21:27

我不确定您是否解决了您的问题,但是现在您可以使用正式的API资源管理器进行API版本控制,这使得Swagger集成变得简单了。您可以看到一个完整的工作示例这里

下面是一个简短的版本,应该适用于您:

代码语言:javascript
复制
static void Register( HttpConfiguration configuration )
{
    var constraintResolver = new DefaultInlineConstraintResolver() { ConstraintMap = { ["apiVersion"] = typeof( ApiVersionRouteConstraint ) } };

    configuration.AddApiVersioning();
    configuration.MapHttpAttributeRoutes( constraintResolver );

    // note: this option is only necessary when versioning by url segment.
    // the SubstitutionFormat property can be used to control the format of the API version
    var apiExplorer = configuration.AddVersionedApiExplorer( options => options.SubstituteApiVersionInUrl = true );

    configuration.EnableSwagger(
                    "{apiVersion}/swagger",
                    swagger =>
                    {
                        // build a swagger document and endpoint for each discovered API version
                        swagger.MultipleApiVersions(
                            ( apiDescription, version ) => apiDescription.GetGroupName() == version,
                            info =>
                            {
                                foreach ( var group in apiExplorer.ApiDescriptions )
                                {
                                    var description = "A sample application with Swagger, Swashbuckle, and API versioning.";

                                    if ( group.IsDeprecated )
                                    {
                                        description += " This API version has been deprecated.";
                                    }

                                    info.Version( group.Name, $"Sample API {group.ApiVersion}" )
                                        .Contact( c => c.Name( "Bill Mei" ).Email( "bill.mei@somewhere.com" ) )
                                        .Description( description )
                                        .License( l => l.Name( "MIT" ).Url( "https://opensource.org/licenses/MIT" ) )
                                        .TermsOfService( "Shareware" );
                                }
                            } );

                        swagger.IncludeXmlComments( XmlCommentsFilePath );
                    } )
                 .EnableSwaggerUi( swagger => swagger.EnableDiscoveryUrlSelector() );
    }
}

static string XmlCommentsFilePath
{
    get
    {
        var basePath = System.AppDomain.CurrentDomain.RelativeSearchPath;
        var fileName = typeof( Startup ).GetTypeInfo().Assembly.GetName().Name + ".xml";
        return Path.Combine( basePath, fileName );
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44775183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档