如何配置swashbuckle以显示api版本而不是v {version}变量?

时间:2018-06-28 01:16:44

标签: c# .net asp.net-web-api swagger swashbuckle

我正在使用Swashbuckle记录我的Web API 2.2 API。当我加载Swagger页面时,uri会显示一个版本占位符变量,而不是实际版本。例如:

/api/v{version}/authentication

代替:

/api/v2/authentication

如何配置我的应用程序或Swashbuckle以显示版本号而不是版本变量?

3 个答案:

答案 0 :(得分:1)

对不起,刚刚注意到您正在谈论URI ...不确定下面是否有帮助

您是否在招摇的配置中尝试了以下类似方法:

public static void Register(HttpConfiguration config)
{
    config
        .EnableSwagger(c =>
        {
            c.SingleApiVersion("v1", "version api");                
            c.PrettyPrint();
            c.OAuth2("oauth2").Description("OAuth2 ResourceOwner Grant").TokenUrl("/testtoken");
            c.IncludeXmlComments(GetXmlCommentsPath());
            c.DocumentFilter<AuthTokenOperation>();
            c.DocumentFilter<ListManagementSwagger>();
            c.SchemaFilter<SchemaExamples>();
        })
        .EnableSwaggerUi(c =>
        {
            c.DocumentTitle("test webapi");                
        });
}

答案 1 :(得分:1)

WebApiConfig的更新代码:

// Web API configuration and services
            var constraintResolver = new System.Web.Http.Routing.DefaultInlineConstraintResolver()
            {
                ConstraintMap =
                {
                    ["apiVersion"] = typeof(Microsoft.Web.Http.Routing.ApiVersionRouteConstraint)
                }
            };

            config.AddVersionedApiExplorer(opt =>
            {
                opt.SubstituteApiVersionInUrl = true;

            });

            config.MapHttpAttributeRoutes(constraintResolver);
            config.AddApiVersioning();

            // Web API routes
            //config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

一些参考文献Swagger

答案 2 :(得分:0)

这是实现版本控制的方法之一。我有一个自定义标头和自定义根url函数,您可以忽略该部分。这段代码要求Swagger从提供的xml构建两个不同的版本。

public class SwaggerConfig
{
    public static void Register()
    {

        var customHeader = new SwaggerHeader  //you can ignore this one
        {
            Description = "Custom header description",
            Key = "customHeaderId",
            Name = "customHeaderId"
        };

        var versionSupportResolver = new Func<ApiDescription, string, bool>((apiDescription, version) =>
        {
            var path = apiDescription.RelativePath.Split('/');
            var pathVersion = path[1];
            return string.Equals(pathVersion, version, StringComparison.OrdinalIgnoreCase);
        });

        var versionInfoBuilder = new Action<VersionInfoBuilder>(info => {
            info.Version("v2", "My API v2");
            info.Version("v1", "My API v1");
        });

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
            {
                //c.RootUrl(ComputeHostAsSeenByOriginalClient);  //you can ignore this custom function
                c.Schemes(new[] { "http", "https" });
                customHeader.Apply(c);
                c.MultipleApiVersions(versionSupportResolver, versionInfoBuilder);
                c.IgnoreObsoleteActions();
                c.IncludeXmlComments(GetXmlCommentsPath());
                c.DescribeAllEnumsAsStrings();
            })
            .EnableSwaggerUi("swagger/ui/{*assetPath}", c =>
            {
                c.DisableValidator();
                c.SupportedSubmitMethods("GET", "POST");
            });
    }

    private static Func<XPathDocument> GetXmlCommentsPath()
    {
        return () =>
        {
            var xapixml = GetXDocument("My.API.xml");
            var xElement = xapixml.Element("doc");
            XPathDocument xPath = null;
            if (xElement != null)
            {
                using (var ms = new MemoryStream())
                {
                    var xws = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false };
                    using (var xw = XmlWriter.Create(ms, xws))
                    {
                        xElement.WriteTo(xw);
                    }
                    ms.Position = 0;
                    xPath = new XPathDocument(ms);
                }
            }
            return xPath;
        };
    }

    private static XDocument GetXDocument(string file)
    {
        var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
        var xDoc = XDocument.Load(path + "\\" + file);
        return xDoc;
    }

    //ComputeHostAsSeenByOriginalClient function code

}