/// <summary> /// Aggiunge a swagger la documentazione relativa agli enumerativi /// </summary> /// <param name="options"></param> public static void AddEnumDocumentation(this SwaggerGenOptions options) { options.SchemaFilter <XEnumNamesSchemaFilter>(); options.ParameterFilter <XEnumNamesParameterFilter>(); options.DocumentFilter <DisplayEnumsWithValuesDocumentFilter>(); options.DocumentFilter <RemoveEnumsDocumentFilter>(); //DA usare DOPO DisplayEnumsWithValuesDocumentFilter }
protected override void Configuration(SwaggerGenOptions options) { var xmlPath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, PlatformServices.Default.Application.ApplicationName + ".xml"); if (File.Exists(xmlPath)) { options.IncludeXmlComments(xmlPath); } options.DescribeAllEnumsAsStrings(); options.OperationFilter <AddFileUploadParams>(); options.DocumentFilter <EndPointPathsAndParamsToLower>(); options.DocumentFilter <SetVersionInPaths>(); options.SchemaFilter <PagedResultSchemaFilter>(); }
/// <summary> /// 显示方法计数 /// </summary> /// <param name="options">Swagger生成选项</param> public static void ShowActionCount(this SwaggerGenOptions options) { if (!options.DocumentFilterDescriptors.Exists(x => x.Type == typeof(AppendActionCountToTagSummaryDocumentFilter))) { options.DocumentFilter <AppendActionCountToTagSummaryDocumentFilter>(); } }
/// <summary> /// 基于控制器进行排序 /// </summary> /// <param name="options">Swagger生成选项</param> /// <param name="orderByDesc">是否降序排序</param> public static void OrderByController(this SwaggerGenOptions options, bool orderByDesc = false) { if (!options.DocumentFilterDescriptors.Exists(x => x.Type == typeof(TagReOrderDocumentFilter))) { options.DocumentFilter <TagReOrderDocumentFilter>(orderByDesc); } }
/// <summary> /// Enables Swagger annotations (SwaggerOperationAttribute, SwaggerParameterAttribute etc.) /// </summary> /// <param name="options"></param> /// <param name="enableAnnotationsForInheritance">Enables SwaggerSubType attribute for inheritance</param> /// <param name="enableAnnotationsForPolymorphism">Enables SwaggerSubType and SwaggerDiscriminator attributes for polymorphism</param> public static void EnableAnnotations( this SwaggerGenOptions options, bool enableAnnotationsForInheritance, bool enableAnnotationsForPolymorphism) { options.SchemaFilter <AnnotationsSchemaFilter>(); options.ParameterFilter <AnnotationsParameterFilter>(); options.RequestBodyFilter <AnnotationsRequestBodyFilter>(); options.OperationFilter <AnnotationsOperationFilter>(); options.DocumentFilter <AnnotationsDocumentFilter>(); if (enableAnnotationsForInheritance || enableAnnotationsForPolymorphism) { options.SelectSubTypesUsing(AnnotationsSubTypesSelector); if (enableAnnotationsForInheritance) { options.UseAllOfForInheritance(); } if (enableAnnotationsForPolymorphism) { options.UseOneOfForPolymorphism(); options.SelectDiscriminatorNameUsing(AnnotationsDiscriminatorNameSelector); options.SelectDiscriminatorValueUsing(AnnotationsDiscriminatorValueSelector); } } }
/// <summary> /// Configure the swagger settings. /// </summary> /// <param name="swaggerGenOptions">The <see cref="SwaggerGenOptions"/> to use.</param> /// <param name="assemblyDocumentationPath">The path to the XML documentation file for the <see cref="Host"/> assembly.</param> /// <param name="apiDocumentationPath">The path to the XML documentation file for the <see cref="Api"/> assembly.</param> public static void Configure(SwaggerGenOptions swaggerGenOptions, string assemblyDocumentationPath, string apiDocumentationPath) { swaggerGenOptions.SwaggerDoc( "v1", new OpenApiInfo { Title = "TGS API", Version = ApiHeaders.Version.Semver().ToString(), License = new OpenApiLicense { Name = "AGPL-3.0", Url = new Uri("https://github.com/tgstation/tgstation-server/blob/dev/LICENSE") }, Contact = new OpenApiContact { Name = "/tg/station 13", Url = new Uri("https://github.com/tgstation") }, Description = "A production scale tool for BYOND server management" }); // Important to do this before applying our own filters // Otherwise we'll get NullReferenceExceptions on parameters to be setup in our document filter swaggerGenOptions.IncludeXmlComments(assemblyDocumentationPath); swaggerGenOptions.IncludeXmlComments(apiDocumentationPath); // nullable stuff swaggerGenOptions.UseAllOfToExtendReferenceSchemas(); swaggerGenOptions.OperationFilter <SwaggerConfiguration>(); swaggerGenOptions.DocumentFilter <SwaggerConfiguration>(); swaggerGenOptions.SchemaFilter <SwaggerConfiguration>(); swaggerGenOptions.CustomSchemaIds(type => { if (type == typeof(Api.Models.Internal.User)) { return("ShallowUser"); } return(type.Name); }); swaggerGenOptions.AddSecurityDefinition(PasswordSecuritySchemeId, new OpenApiSecurityScheme { In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Name = HeaderNames.Authorization, Scheme = ApiHeaders.BasicAuthenticationScheme }); swaggerGenOptions.AddSecurityDefinition(TokenSecuritySchemeId, new OpenApiSecurityScheme { BearerFormat = "JWT", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Name = HeaderNames.Authorization, Scheme = ApiHeaders.JwtAuthenticationScheme }); }
private static void configureSwaggerGen(SwaggerGenOptions options) { addSwaggerDocs(options); options.OperationFilter <RemoveVersionFromParameter>(); options.DocumentFilter <ReplaceVersionWithExactValueInPath>(); options.DocInclusionPredicate((version, desc) => { if (!desc.TryGetMethodInfo(out var methodInfo)) { return(false); } var versions = methodInfo .DeclaringType? .GetCustomAttributes(true) .OfType <ApiVersionAttribute>() .SelectMany(attr => attr.Versions); var maps = methodInfo .GetCustomAttributes(true) .OfType <MapToApiVersionAttribute>() .SelectMany(attr => attr.Versions) .ToList(); return(versions?.Any(v => $"v{v}" == version) == true && (!maps.Any() || maps.Any(v => $"v{v}" == version))); }); }
/// <summary> /// Swagger 生成器构建 /// </summary> /// <param name="swaggerGenOptions">Swagger 生成器配置</param> /// <param name="configure">自定义配置</param> internal static void BuildGen(SwaggerGenOptions swaggerGenOptions, Action <SwaggerGenOptions> configure = null) { // 创建分组文档 CreateSwaggerDocs(swaggerGenOptions); // 加载分组控制器和动作方法列表 LoadGroupControllerWithActions(swaggerGenOptions); // 配置 Swagger SchemaId ConfigureSchemaId(swaggerGenOptions); // 配置标签 ConfigureTagsAction(swaggerGenOptions); // 配置 Action 排序 ConfigureActionSequence(swaggerGenOptions); // 加载注释描述文件 LoadXmlComments(swaggerGenOptions); // 配置授权 ConfigureSecurities(swaggerGenOptions); //使得Swagger能够正确地显示Enum的对应关系 swaggerGenOptions.SchemaFilter <EnumSchemaFilter>(); // 支持控制器排序操作 swaggerGenOptions.DocumentFilter <TagsOrderDocumentFilter>(); // 自定义配置 configure?.Invoke(swaggerGenOptions); }
public void Configure(SwaggerGenOptions options) { options.OperationFilter <TSwaggerResponseDefinitions>(); var xmlPath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, PlatformServices.Default.Application.ApplicationName + ".xml"); if (File.Exists(xmlPath)) { options.IncludeXmlComments(xmlPath); } options.OperationFilter <AddFileUploadParams>(); options.OperationFilter <AddConsumeProducesValues>(); options.DocumentFilter <SetVersionInPaths>(); options.SchemaFilter <PagedResultSchemaFilter>(); options.DocumentFilter <EndPointPathsAndParamsToLower>(); Configuration(options); }
public static void UseSchemes(this SwaggerGenOptions documentOptions, Action <ISet <string> > schemesBuilder) { var schemes = new HashSet <string>(); schemesBuilder(schemes); documentOptions.DocumentFilter <SchemesDocumentFilter>(schemes); }
public static SwaggerGenOptions ConfigureForNetTopologySuite(this SwaggerGenOptions c) { c.DocumentFilter <DocumentFilter>(); c.MapType <Geometry>( () => new OpenApiSchema { ExternalDocs = new OpenApiExternalDocs { Url = new Uri("http://geojson.org/geojson-spec.html#geometry-objects"), }, Type = "object", Extensions = new Dictionary <string, IOpenApiExtension> { ["clrType"] = new OpenApiString(typeof(Geometry).FullName) }, Description = "GeoJSon geometry", Discriminator = new OpenApiDiscriminator { PropertyName = "type", }, Required = new HashSet <string> { "type" }, Properties = new Dictionary <string, OpenApiSchema> {
public static void Config(this SwaggerGenOptions options) { options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "Bearer" }); options.OperationFilter <AuthenticationRequirementsOperationFilter>(); //This action return true/false after selected SwaggerDoc section for add/decline Request options.DocInclusionPredicate((docName, apiDescription) => docName == apiDescription.GroupName); var swaggerFiles = new string[] { "SwaggerAPI.xml", "SwaggerApplicationAPI.xml" } .Select(fileName => Path.Combine(System.AppContext.BaseDirectory, fileName)) .Where(filePath => File.Exists(filePath)); foreach (var filePath in swaggerFiles) { options.IncludeXmlComments(filePath); } options.OperationFilter <ObjectIdOperationFilter>(swaggerFiles); options.SchemaFilter <ObjectIdSchemaFilter>(); options.OperationFilter <DateTimeOperationFilter>(); options.SchemaFilter <DateTimeSchemaFilter>(); //should be the last ones options.OperationFilter <LowercaseOperationFilter>(); options.DocumentFilter <LowercaseDocumentFilter>(); }
public static void AddAuthenticationConfig(this SwaggerGenOptions c, AuthenticationType authenticationType) { switch (authenticationType) { case AuthenticationType.JwtBearer: var tokenPath = TokenConfiguration.GetOptions().Value.Path; c.DocumentFilter <TokenOperation>(); c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, c.GetTokenSecurityDefinition(tokenPath)); c.AddSecurityRequirement(c.GetTokenSecurityRequirement()); break; case AuthenticationType.Basic: c.AddSecurityDefinition(BasicAuthenticationDefaults.AuthenticationScheme, c.GetBasicSecurityDefinition()); c.AddSecurityRequirement(c.GetBasicSecurityRequirement()); break; case AuthenticationType.ApiKey: c.AddSecurityDefinition(ApiKeyAuthenticationDefaults.AuthenticationScheme, c.GetApiKeySecurityDefinition()); c.AddSecurityRequirement(c.GetApiKeySecurityRequirement()); break; case AuthenticationType.AllowAll: break; default: throw new ArgumentException(nameof(authenticationType) + " is not a valid authentication type"); } }
public static void EnableAnnotations(this SwaggerGenOptions options) { options.SchemaFilter <AnnotationsSchemaFilter>(); options.ParameterFilter <AnnotationsParameterFilter>(); options.OperationFilter <AnnotationsOperationFilter>(); options.DocumentFilter <AnnotationsDocumentFilter>(); }
private static void ConfigureSwagger(SwaggerGenOptions options) { options.SwaggerDoc("v1", new Info { Version = "v1", Title = "Computer Vision as Service API", Description = "A simple api to run computer vision algorithms.", TermsOfService = "None", Contact = new Contact { Name = "Adam Jež", Email = "*****@*****.**" } }); options.AddSecurityDefinition("ApiKey", new ApiKeyScheme() { In = "header", Name = "Authorization", Description = "Api Key Authentication", Type = "apiKey" }); options.DocumentFilter <LowercaseDocumentFilter>(); options.OperationFilter <AuthResponsesOperationFilter>(); options.OperationFilter <AddFileParamsFilter>(); var basePath = PlatformServices.Default.Application.ApplicationBasePath; var pathToDoc = System.IO.Path.Combine(basePath, "CVaS.Web.xml"); options.IncludeXmlComments(pathToDoc); }
public void ConfigureSwaggerDocumentation(SwaggerGenOptions opts) { // version 1 of API opts.SwaggerDoc("v1", new OpenApiInfo { Version = "v1.0", Title = "ToDo API v1" }); //version 2 of API opts.SwaggerDoc("v2", new OpenApiInfo { Version = "v2", Title = "ToDo API v2" }); opts.DocumentFilter <ReplaceVersionWithExactValueInPath>(); opts.OperationFilter <RemoveVersionFromParameter>(); opts.DocInclusionPredicate((version, desc) => { var versions = desc.CustomAttributes().OfType <ApiVersionAttribute>().SelectMany(attr => attr.Versions); var res = versions.Any(v => $"v{v.MajorVersion.ToString()}" == version); return(res); }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); opts.IncludeXmlComments(xmlPath); }
public static void Configure(SwaggerGenOptions options) { options.SwaggerDoc(SwaggerConstants.InvestorsGroup, new Info { Title = SwaggerConstants.InvestorsTitle, Version = "1.0" }); options.SwaggerDoc(SwaggerConstants.AdministratorsGroup, new Info { Title = SwaggerConstants.AdministratorsTitle, Version = "1.0" }); options.SwaggerDoc(SwaggerConstants.AnalyticsGroup, new Info { Title = SwaggerConstants.AnalyticsTitle, Version = "1.0" }); options.DescribeAllEnumsAsStrings(); options.OperationFilter <SwaggerExamplesDocumentFilter>(); options.DocumentFilter <SwaggerDescriptionDocumentFilter>("InvestorApi.Swagger.Documentation.md"); options.IncludeXmlComments(AppContext.BaseDirectory + "InvestorApi.xml"); options.IncludeXmlComments(AppContext.BaseDirectory + "InvestorApi.Contracts.xml"); options.AddSecurityDefinition("Bearer", new ApiKeyScheme() { Description = "Enter: Bearer {token}", Name = "Authorization", In = "header", Type = "apiKey" }); }
/// <summary> /// 显示枚举描述 /// </summary> /// <param name="options">Swagger生成选项</param> public static void ShowEnumDescription(this SwaggerGenOptions options) { if (options.DocumentFilterDescriptors.Exists(x => x.Type == typeof(AddEnumDescriptionsDocumentFilter))) { return; } options.DocumentFilter <AddEnumDescriptionsDocumentFilter>(); }
public static void AddXAmazonApiGatewayAnnotations(this SwaggerGenOptions swaggerGenOptions, Action <XAmazonApiGatewayOptions> setupAction) { var options = new XAmazonApiGatewayOptions(); setupAction.Invoke(options); swaggerGenOptions.DocumentFilter <XAmazonApiGatewayDocumentFilter>(options); }
public static void WithDocumentTags(this SwaggerGenOptions swaggerGenOptions, Action <DocumentTagsConfig> setupAction) { var options = new DocumentTagsConfig(); setupAction.Invoke(options); swaggerGenOptions.DocumentFilter <DocumentTagsDocumentFilter>(options); }
/// <summary> /// Confgures Swaschbuckle to provide additional metadata in methods which use FromQuery attribute so the API provided by DotVVM API generator is easier to use. /// </summary> public static void EnableDotvvmIntegration(this SwaggerGenOptions options) { options.OperationFilter <RemoveReadOnlyFromUriParametersOperationFilter>(); options.OperationFilter <RemoveBindNoneFromUriParametersOperationFilter>(); options.OperationFilter <AddAsObjectOperationFilter>(); options.SchemaFilter <AddTypeToModelSchemaFilter>(); options.DocumentFilter <HandleKnownTypesDocumentFilter>(); }
public void ConfigureSwaggerDocumentation(SwaggerGenOptions opts) { // version 1 of API opts.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "Cars API v1", Description = "A simple example ASP.NET Core Web API", TermsOfService = new Uri("https://example.com/terms"), Contact = new OpenApiContact { Name = "Kaan Uzun", Email = string.Empty, Url = new Uri("https://twitter.com/"), }, License = new OpenApiLicense { Name = "Use under LICX", Url = new Uri("https://example.com/license"), } }); //version 2 of API opts.SwaggerDoc("v2", new OpenApiInfo { Version = "v2", Title = "Cars API v2", Description = "Another simple example ASP.NET Core Web API", TermsOfService = new Uri("https://example.com/terms"), Contact = new OpenApiContact { Name = "Angel Gomez", Email = string.Empty, Url = new Uri("https://twitter.com/"), }, License = new OpenApiLicense { Name = "Use under LICX", Url = new Uri("https://example.com/license"), } }); opts.DocumentFilter <ReplaceVersionWithExactValueInPath>(); // replace version opts.OperationFilter <RemoveVersionFromParameter>(); opts.DocInclusionPredicate((version, desc) => { var versions = desc.CustomAttributes().OfType <ApiVersionAttribute>().SelectMany(attr => attr.Versions); var res = versions.Any(v => $"v{v.MajorVersion.ToString()}" == version); return(res); }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); opts.IncludeXmlComments(xmlPath); }
public static void WithDocumentTags(this SwaggerGenOptions swaggerGenOptions, IEnumerable <OpenApiTag> tags) { var options = new DocumentTagsConfig { Tags = tags }; swaggerGenOptions.DocumentFilter <DocumentTagsDocumentFilter>(options); }
/// <summary> /// Change all responses by specific http status codes in OpenApi document. /// </summary> /// <typeparam name="T">Type of response example.</typeparam> /// <param name="swaggerGenOptions"><see cref="SwaggerGenOptions"/>.</param> /// <param name="httpStatusCode">HTTP status code.</param> /// <param name="responseDescription">Response description.</param> /// <param name="responseExampleOption"><see cref="ResponseExampleOptions"/>.</param> /// <param name="responseExample">New example for response.</param> /// <returns> /// Returns <see cref="SwaggerGenOptions"/>. /// </returns> public static SwaggerGenOptions ChangeAllResponsesByHttpStatusCode <T>( this SwaggerGenOptions swaggerGenOptions, int httpStatusCode, string responseDescription = null, ResponseExampleOptions responseExampleOption = ResponseExampleOptions.None, T responseExample = default) where T : class { swaggerGenOptions.DocumentFilter <ChangeResponseByHttpStatusCodeDocumentFilter <T> >(httpStatusCode, responseDescription, responseExampleOption, responseExample); return(swaggerGenOptions); }
/// <summary> /// Enables microsoft extension generation /// </summary> /// <param name="filePicker">File picker capability used for microsoft extension generation</param> public static void GenerateMicrosoftExtensions(this SwaggerGenOptions options, FilePickerCapabilityModel filePicker = null) { options.OperationFilter <OperationFilter>(); options.SchemaFilter <SchemaFilter>(); if (filePicker != null) { options.DocumentFilter <CapabilityFilter>(filePicker); } }
//TODO MJ public static void AddPolymorphismSupport <TBase>(this SwaggerGenOptions o, string discriminatorName = "discriminator", HashSet <Type> derivedTypes = null) { if (derivedTypes == null || derivedTypes.Count == 0) { derivedTypes = _init <TBase>(); } o.DocumentFilter <PolymorphismDocumentFilter <TBase> >(discriminatorName, derivedTypes); o.SchemaFilter <PolymorphismSchemaFilter <TBase> >(derivedTypes); }
/// <summary> /// 添加文档过滤器 /// </summary> /// <typeparam name="TDocumentFilter">文档过滤器类型</typeparam> /// <param name="options">Swagger生成选项</param> /// <param name="arguments">参数</param> internal static void AddDocumentFilter <TDocumentFilter>(this SwaggerGenOptions options, params object[] arguments) where TDocumentFilter : IDocumentFilter { if (options.DocumentFilterDescriptors.Exists(x => x.Type == typeof(TDocumentFilter))) { return; } options.DocumentFilter <TDocumentFilter>(arguments); }
public void Configure(SwaggerGenOptions options) { foreach (var description in _provider.ApiVersionDescriptions) { options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description)); } options.OperationFilter <RemoveVersionFromParameter>(); options.DocumentFilter <ReplaceVersionWithExactValueInPath>(); options.ResolveConflictingActions(apiDescriptions => apiDescriptions.FirstOrDefault()); }
/// <summary> /// Inject human-friendly descriptions for Operations, Parameters and Schemas based on XML Comment files /// </summary> /// <param name="swaggerGenOptions"></param> /// <param name="xmlDocFactory">A factory method that returns XML Comments as an XPathDocument</param> /// <param name="includeControllerXmlComments"> /// Flag to indicate if controller XML comments (i.e. summary) should be used to assign Tag descriptions. /// Don't set this flag if you're customizing the default tag for operations via TagActionsBy. /// </param> public static void IncludeAuthorizationXmlComments(this SwaggerGenOptions swaggerGenOptions, Func <XPathDocument> xmlDocFactory, bool includeControllerXmlComments = false) { XPathDocument xpathDocument = xmlDocFactory(); swaggerGenOptions.OperationFilter <AuthorizationXmlCommentsOperationFilter>((object)xpathDocument); swaggerGenOptions.SchemaFilter <XmlCommentsSchemaFilter>((object)xpathDocument); if (!includeControllerXmlComments) { return; } swaggerGenOptions.DocumentFilter <XmlCommentsDocumentFilter>((object)xpathDocument); }
internal static void ConfigureSwagger(SwaggerGenOptions c) { c.SwaggerDoc("v1", new OpenApiInfo() { Title = "My API", Version = "v1" }); c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml")); c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"JoinRpg.Web.XGameApi.Contract.xml")); c.DocumentFilter <SwaggerXGameApiFilter>(); }