简体   繁体   中英

how can I configure swashbuckle to display the api version instead of the v{version} variable?

I'm using Swashbuckle to document my Web API 2.2 API. When I load the Swagger page, the uri's display with a version placeholder variable instead of the actual version. For example:

/api/v{version}/authentication

Instead of:

/api/v2/authentication

How can I configure my app or Swashbuckle to display the version number instead of the version variable?

Sorry, just noticed you are talking about the URI ...not sure if below will help

Have you tried something like below in your swagger config :

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");                
        });
}

Updated code for 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 }
            );

Some references Swagger

This is one of the ways to implement versioning. I have a custom header and custom root url function, you can ignore that part. This code is asking Swagger to build two different versions from the xml provided.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM