使用Microsoft.AspNet.Versioning的SwashBuckle Swagger版本控制未在swagger文档中显示任何api

时间:2020-07-29 09:05:50

标签: swagger versioning swashbuckle webapi

我创建了一个Web api项目,而不是使用swashbuckle实现了摇摇欲坠。 比我已经使用Microsoft.AspNet.Versioning和Microsoft.AspNet.Versioning.ApiExplorer实现版本控制之后。 比我在招摇页面上运行该应用程序没有显示任何错误 但是我那张狂的文件没有在列表页面上显示任何api

Herer是我的webapiconfig.cs文件,如下所示

using System.Web.Http;
using System.Web.Http.Routing;
using Microsoft.Owin.Security.OAuth;
using Microsoft.Web.Http;
using Microsoft.Web.Http.Routing;
using Microsoft.Web.Http.Versioning.Conventions;
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

           
            config.AddApiVersioning(
               options =>
               {
                    // reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
                    options.ReportApiVersions = true;
                   options.Conventions.Add(new VersionByNamespaceConvention());
                   options.DefaultApiVersion = new ApiVersion(1,0);
               });
            var constraintResolver = new DefaultInlineConstraintResolver
            {
                ConstraintMap ={["apiVersion"] = typeof(ApiVersionRouteConstraint)}
            };
            config.MapHttpAttributeRoutes(constraintResolver);
            config.AddApiVersioning(c=>c.AssumeDefaultVersionWhenUnspecified=true);
          
            config.Routes.MapHttpRoute(
                  name: "DefaultApi",
                  routeTemplate: "api/v{apiVersion}/{controller}/{action}/{id}",
                  defaults: new { id = RouteParameter.Optional }
              );
        }
    }

我的swaggerconfig.cs文件如下

using System.Web.Http;
using WebActivatorEx;
using RAC.API;
using Swashbuckle.Application;
using System.Configuration;
using Swashbuckle.Swagger;
using System.Web.Http.Description;
using System.Linq;
using System.Web.Http.Filters;
using System.Collections.Generic;
using Microsoft.Web.Http.Description;

[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]

namespace RAC.API
{
   public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
            var isAuthorized = filterPipeline
                .Select(filterInfo => filterInfo.Instance)
                .Any(filter => filter is IAuthorizationFilter);

            var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();

            if (!isAuthorized || allowAnonymous) return;

            if (operation.parameters == null) operation.parameters = new List<Parameter>();
            
            operation.parameters.Add(new Parameter 
            {
                name = "Authorization",
                @in = "header",
                description = "access token",
                required = true,
                type = "string"
            });
        }
    }

   
    public class SwaggerDefaultValues : IOperationFilter
    {
        public void Apply(
          Operation operation,
          SchemaRegistry schemaRegistry,
          ApiDescription apiDescription)
        {
            if (apiDescription is VersionedApiDescription versionedApiDescription)
            {
                operation.deprecated = versionedApiDescription.IsDeprecated;
            }

            if (operation.parameters == null)
            {
                return;
            }

            foreach (var parameter in operation.parameters)
            {
                var description = apiDescription.ParameterDescriptions
                                                .First(p => p.Name == parameter.name);

                if (parameter.description == null)
                {
                    parameter.description = description.Documentation;
                }

                if (parameter.@default == null)
                {
                    parameter.@default = description.ParameterDescriptor?.DefaultValue;
                }
            }
        }
    }

    public class SwaggerConfig
    {
        public static void Register()
        {
            var ApiVersion = ConfigurationManager.AppSettings["ApiVersion"].ToString();
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                    {
                       
                        c.MultipleApiVersions(
                            (apiDesc, targetApiVersion) => ResolveVersionSupportByRouteConstraint(apiDesc, targetApiVersion),
                            (vc) =>
                            {
                               // vc.Version("v2", "RAC API V2");
                                vc.Version("v1", "RAC API V1");
                            });
                        c.OperationFilter(() => new AddAuthorizationHeaderParameterOperationFilter());
                        c.OperationFilter<SwaggerDefaultValues>();
                       
                        c.IncludeXmlComments(string.Format(@"{0}\bin\RAC.API.xml",System.AppDomain.CurrentDomain.BaseDirectory));
                       
                    })
                .EnableSwaggerUi(c =>
                    {
                        
                        c.DocumentTitle("RAC API");
                        c.EnableDiscoveryUrlSelector();

                    });
        }

        private static bool ResolveVersionSupportByRouteConstraint(ApiDescription apiDesc, string targetApiVersion)
        {
            return apiDesc.ActionDescriptor.ControllerDescriptor.ControllerType.FullName.Contains($"{targetApiVersion}.");
        }
    }
}

0 个答案:

没有答案