【问题标题】:how can I configure swashbuckle to display the api version instead of the v{version} variable?如何配置 swashbuckle 以显示 api 版本而不是 v{version} 变量?
【发布时间】:2018-12-06 23:26:13
【问题描述】:

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

/api/v{version}/authentication

代替:

/api/v2/authentication

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

【问题讨论】:

  • 仅凭这几个细节很难提供准确的答案...@Sanmoy您能否提供一个重现您的问题的示例项目

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


【解决方案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

【讨论】:

  • 我没有使用 asp.net core
  • 很高兴知道!如果您指出该代码会容易得多,这样人们就会知道您使用的是什么。无论如何,我已经将我的代码更新为您正在使用的正确类型的 ASP.Net。
【解决方案2】:

抱歉,刚刚注意到您在谈论 URI ...不确定以下是否有帮助

你有没有在你的 swagger 配置中尝试过类似下面的东西:

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

【讨论】:

    【解决方案3】:

    这是实现版本控制的方法之一。我有一个自定义标题和自定义根 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
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-17
      • 2022-12-21
      • 2021-04-10
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多