private HttpContent ContentFor(HttpRequestMessage request, SwaggerDocument swaggerDoc) { var negotiator = request.GetConfiguration().Services.GetContentNegotiator(); var result = negotiator.Negotiate(typeof(SwaggerDocument), request, GetSupportedSwaggerFormatters()); return new ObjectContent(typeof(SwaggerDocument), swaggerDoc, result.Formatter, result.MediaType); }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { Contract.Assume(swaggerDoc != null); Contract.Assume(schemaRegistry != null); Contract.Assume(apiExplorer != null); var pathItems = swaggerDoc.paths.Values; var deletes = pathItems.Select(pathItem => pathItem.delete).Where(operation => operation != null); var gets = pathItems.Select(pathItem => pathItem.get).Where(operation => operation != null); var heads = pathItems.Select(pathItem => pathItem.head).Where(operation => operation != null); var patches = pathItems.Select(pathItem => pathItem.patch).Where(operation => operation != null); var puts = pathItems.Select(pathItem => pathItem.put).Where(operation => operation != null); var posts = pathItems.Select(pathItem => pathItem.post).Where(operation => operation != null); var options = pathItems.Select(pathItem => pathItem.options).Where(operation => operation != null); var allOperations = deletes.ConcatEvenIfNull(gets) .ConcatEvenIfNull(heads) .ConcatEvenIfNull(patches) .ConcatEvenIfNull(puts) .ConcatEvenIfNull(posts) .ConcatEvenIfNull(options) .ToList(); AppendParameterNamesToOperationId(allOperations); UniquifyOperationId(allOperations); }
private SwaggerDocument MergeODataAndWebApiSwaggerDocs(string rootUrl, string apiVersion, SwaggerDocument odataSwaggerDoc) { Contract.Requires(odataSwaggerDoc != null); var webApiSwaggerDoc = _defaultProvider.GetSwagger(rootUrl, apiVersion); Contract.Assume(webApiSwaggerDoc != null); webApiSwaggerDoc.paths = webApiSwaggerDoc.paths.UnionEvenIfNull(odataSwaggerDoc.paths).ToLookup(pair => pair.Key, pair => pair.Value) .ToDictionary(group => group.Key, group => group.First()); webApiSwaggerDoc.definitions = webApiSwaggerDoc.definitions.UnionEvenIfNull(odataSwaggerDoc.definitions).ToLookup(pair => pair.Key, pair => pair.Value) .ToDictionary(group => group.Key, group => group.First()); webApiSwaggerDoc.parameters = webApiSwaggerDoc.parameters.UnionEvenIfNull(odataSwaggerDoc.parameters).ToLookup(pair => pair.Key, pair => pair.Value) .ToDictionary(group => group.Key, group => group.First()); webApiSwaggerDoc.responses = webApiSwaggerDoc.responses.UnionEvenIfNull(odataSwaggerDoc.responses).ToLookup(pair => pair.Key, pair => pair.Value) .ToDictionary(group => group.Key, group => group.First()); webApiSwaggerDoc.securityDefinitions = webApiSwaggerDoc.securityDefinitions.UnionEvenIfNull(odataSwaggerDoc.securityDefinitions).ToLookup(pair => pair.Key, pair => pair.Value) .ToDictionary(group => group.Key, group => group.First()); webApiSwaggerDoc.vendorExtensions = webApiSwaggerDoc.vendorExtensions.UnionEvenIfNull(odataSwaggerDoc.vendorExtensions).ToLookup(pair => pair.Key, pair => pair.Value) .ToDictionary(group => group.Key, group => group.First()); webApiSwaggerDoc.tags = webApiSwaggerDoc.tags.UnionEvenIfNull(odataSwaggerDoc.tags, new TagComparer()).ToList(); webApiSwaggerDoc.consumes = webApiSwaggerDoc.consumes.UnionEvenIfNull(odataSwaggerDoc.consumes).ToList(); webApiSwaggerDoc.security = webApiSwaggerDoc.security.UnionEvenIfNull(odataSwaggerDoc.security).ToList(); webApiSwaggerDoc.produces = webApiSwaggerDoc.produces.UnionEvenIfNull(odataSwaggerDoc.produces).ToList(); webApiSwaggerDoc.schemes = webApiSwaggerDoc.schemes.UnionEvenIfNull(odataSwaggerDoc.schemes).ToList(); return webApiSwaggerDoc; }
/// <summary> /// /// </summary> /// <param name="swaggerDoc"></param> /// <param name="schemaRegistry"></param> /// <param name="apiExplorer"></param> public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { IList<string> apilist = new List<string>(); if (swaggerDoc != null && swaggerDoc.paths != null) { foreach (System.Collections.Generic.KeyValuePair<string, PathItem> pathitem in swaggerDoc.paths) { if (pathitem.Key.Contains("OAuth")) { apilist.Add(pathitem.Key); } } } foreach (string pathitem in apilist) { swaggerDoc.paths.Remove(pathitem); } if (swaggerDoc != null && swaggerDoc.definitions != null) { swaggerDoc.definitions.Remove("TokenResult"); swaggerDoc.definitions.Remove("Object"); } }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.basePath = "/" + swaggerDoc.info.version; swaggerDoc.paths = swaggerDoc.paths.ToDictionary( entry => entry.Key.Replace("/{apiVersion}", ""), entry => RemoveVersionParamsFrom(entry.Value)); }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, System.Web.Http.Description.IApiExplorer apiExplorer) { IList<IDictionary<string, IEnumerable<string>>> security = new List<IDictionary<string, IEnumerable<string>>>(); security.Add(new Dictionary<string, IEnumerable<string>> { {Key, new string[0]} }); swaggerDoc.security = security; }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { //添加Tag swaggerDoc.tags = new List<Tag>(); var controllers = apiExplorer.ApiDescriptions.Select(p => p.ActionDescriptor.ControllerDescriptor).Distinct(); foreach (var item in controllers) { var desc = item.GetCustomAttributes<DisplayNameAttribute>(); if (desc != null && desc.Count > 0) { //hack swaggerDoc.tags.Add(new Tag() { name = hackcontrollername(item.ControllerName), description = desc[0].DisplayName }); } else { var desc2 = item.GetCustomAttributes<DescriptionAttribute>(); if (desc2 != null && desc2.Count > 0) { swaggerDoc.tags.Add(new Tag() { name = hackcontrollername(item.ControllerName), description = desc2[0].Description }); } } } //优化枚举显示 foreach (var schemaDictionaryItem in swaggerDoc.definitions) { var schema = schemaDictionaryItem.Value; foreach (var propertyDictionaryItem in schema.properties) { var property = propertyDictionaryItem.Value; var propertyEnums = property.@enum; if (propertyEnums != null && propertyEnums.Count > 0) { var enumDescriptions = new List<string>(); for (int i = 0; i < propertyEnums.Count; i++) { var enumOption = propertyEnums[i]; var desc =(DisplayAttribute) enumOption.GetType().GetField(enumOption.ToString()).GetCustomAttributes(true).Where(p => p is DisplayAttribute).FirstOrDefault(); if (desc==null) { enumDescriptions.Add(string.Format("{0} = {1} ", Convert.ToInt32(enumOption), Enum.GetName(enumOption.GetType(), enumOption))); } else { enumDescriptions.Add(string.Format("{0} = {1} ", Convert.ToInt32(enumOption), desc.Name)); } } property.description += string.Format(" ({0})", string.Join(", ", enumDescriptions.ToArray())); } } } }
private void RespondWithSwaggerJson(HttpResponse response, SwaggerDocument swagger) { response.StatusCode = 200; response.ContentType = "application/json"; using (var writer = new StreamWriter(response.Body)) { _swaggerSerializer.Serialize(writer, swagger); } }
/// <summary> /// Apply function /// </summary> /// <param name="swaggerDoc"></param> /// <param name="schemaRegistry"></param> /// <param name="apiExplorer"></param> public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { try { swaggerDoc.paths.Remove("/{url}"); swaggerDoc.paths.Remove("/Error"); } catch (Exception ex) { Console.WriteLine(ex); } }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.tags = new List<Tag> { new Tag { name = "Clients", description = "an ApiController resource" }, new Tag { name = "Customers", description = "an ODataController resource" }, new Tag { name = "Orders", description = "an ODataController resource" }, new Tag { name = "CustomersV1", description = "a versioned ODataController resource" }, new Tag { name = "Users", description = "a RESTier resource" }, new Tag { name = "Products", description = "demonstrates OData functions and actions" } }; }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.tags = new List<Tag> { new Tag { name = "Clients", description = "an ApiController resource" }, new Tag { name = "Customers", description = "an ODataController resource" }, new Tag { name = "Orders", description = "an ODataController resource" }, new Tag { name = "CustomersV1", description = "a versioned ODataController resource" }, new Tag { name = "Users", description = "a RESTier resource" }, new Tag { name = "Products", description = "demonstrates OData functions and actions" }, new Tag { name = "ProductWithCompositeEnumIntKeys", description = "demonstrates composite keys with an enum as a key" }, new Tag { name = "ProductWithEnumKeys", description = "demonstrates use of enum as a key" }, }; }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { var thisAssemblyTypes = Assembly.GetExecutingAssembly().GetTypes().ToList(); var controllers = Assembly.GetExecutingAssembly().GetTypes().Where(type => typeof(ApiController).IsAssignableFrom(type)); var odataRoutes = GlobalConfiguration.Configuration.Routes.Where(a => a.GetType() == typeof(ODataRoute)).ToList(); var route = odataRoutes.FirstOrDefault() as ODataRoute; foreach (Type controller in controllers) { string name = controller.Name.Replace("Controller", ""); if (swaggerDoc.paths.Keys.Contains("/Api/" + name)) { swaggerDoc.paths["/Api/" + name].get = null; } } }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { foreach (var apiDescription in apiExplorer.ApiDescriptions) { if ( !apiDescription.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<SwHideInDocsAttribute>() .Any() && !apiDescription.ActionDescriptor.GetCustomAttributes<SwHideInDocsAttribute>().Any()) { continue; } var route = "/" + apiDescription.Route.RouteTemplate.TrimEnd('/'); swaggerDoc.paths.Remove(route); } }
public SwaggerDocument GetSwagger(string rootUrl, string apiVersion) { var swashbuckleOptions = _config.GetSwashbuckleOptions(); var schemaRegistry = new SchemaRegistry( _config.Configuration.SerializerSettingsOrDefault(), swashbuckleOptions.CustomSchemaMappings, swashbuckleOptions.SchemaFilters, swashbuckleOptions.ModelFilters, swashbuckleOptions.IgnoreObsoleteProperties, swashbuckleOptions.SchemaIdSelector, swashbuckleOptions.DescribeAllEnumsAsStrings, swashbuckleOptions.DescribeStringEnumsInCamelCase); Info info; _config.GetApiVersions().TryGetValue(apiVersion, out info); if (info == null) throw new UnknownApiVersion(apiVersion); var paths = GetApiDescriptionsFor(apiVersion) .Where(apiDesc => !(swashbuckleOptions.IgnoreObsoleteActions && apiDesc.IsObsolete())) .OrderBy(swashbuckleOptions.GroupingKeySelector, swashbuckleOptions.GroupingKeyComparer) .GroupBy(apiDesc => apiDesc.RelativePathSansQueryString()) .ToDictionary(group => "/" + group.Key, group => CreatePathItem(@group, schemaRegistry)); var rootUri = new Uri(rootUrl); var port = !rootUri.IsDefaultPort ? ":" + rootUri.Port : string.Empty; var odataSwaggerDoc = new SwaggerDocument { info = info, host = rootUri.Host + port, basePath = rootUri.AbsolutePath != "/" ? rootUri.AbsolutePath : null, schemes = swashbuckleOptions.Schemes?.ToList() ?? new[] { rootUri.Scheme }.ToList(), paths = paths, definitions = schemaRegistry.Definitions, securityDefinitions = swashbuckleOptions.SecurityDefinitions }; foreach(var filter in swashbuckleOptions.DocumentFilters) { Contract.Assume(filter != null); filter.Apply(odataSwaggerDoc, schemaRegistry, _config.GetApiExplorer()); } return MergeODataAndWebApiSwaggerDocs(rootUrl, apiVersion, odataSwaggerDoc); }
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) { swaggerDoc.Paths = swaggerDoc.Paths.ToDictionary( entry => entry.Key.Replace("{version}", swaggerDoc.Info.Version), entry => { var pathItem = entry.Value; RemoveVersionParamFrom(pathItem.Get); RemoveVersionParamFrom(pathItem.Put); RemoveVersionParamFrom(pathItem.Post); RemoveVersionParamFrom(pathItem.Delete); RemoveVersionParamFrom(pathItem.Options); RemoveVersionParamFrom(pathItem.Head); RemoveVersionParamFrom(pathItem.Patch); return pathItem; }); }
public SwaggerDocument GetSwagger(string rootUrl, string apiVersion) { var schemaRegistry = new SchemaRegistry( _jsonSerializerSettings, _options.CustomSchemaMappings, _options.SchemaFilters, _options.ModelFilters, _options.IgnoreObsoleteProperties, _options.SchemaIdSelector, _options.DescribeAllEnumsAsStrings, _options.DescribeStringEnumsInCamelCase); Info info; _apiVersions.TryGetValue(apiVersion, out info); if (info == null) throw new UnknownApiVersion(apiVersion); var paths = GetApiDescriptionsFor(apiVersion) .Where(apiDesc => !(_options.IgnoreObsoleteActions && apiDesc.IsObsolete())) .Where(apiDesc => !apiDesc.IsSwaggerIgnore()) .OrderBy(_options.GroupingKeySelector, _options.GroupingKeyComparer) .GroupBy(apiDesc => apiDesc.RelativePathSansQueryString()) .ToDictionary(group => "/" + group.Key, group => CreatePathItem(group, schemaRegistry)); var rootUri = new Uri(rootUrl); var port = (!rootUri.IsDefaultPort) ? ":" + rootUri.Port : string.Empty; var swaggerDoc = new SwaggerDocument { info = info, host = rootUri.Host + port, basePath = (rootUri.AbsolutePath != "/") ? rootUri.AbsolutePath : null, schemes = (_options.Schemes != null) ? _options.Schemes.ToList() : new[] { rootUri.Scheme }.ToList(), paths = paths, definitions = schemaRegistry.Definitions, securityDefinitions = _options.SecurityDefinitions }; foreach (var filter in _options.DocumentFilters) { filter.Apply(swaggerDoc, schemaRegistry, _apiExplorer); } return swaggerDoc; }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { foreach (var definition in swaggerDoc.definitions) { if (IsEntityType(definition)) { var schema = definition.Value; Contract.Assume(schema != null); var properties = schema.properties.ToList(); foreach (var property in schema.properties) { RemoveCollectionTypeProperty(property, properties); RemoveReferenceTypeProperty(property, properties); } schema.properties = properties.ToDictionary(property => property.Key, property => property.Value); } } }
public SwaggerDocument GetSwagger( string apiVersion, string host = null, string basePath = null, string[] schemes = null) { var schemaRegistry = _schemaRegistryFactory.Create(); var info = _options.ApiVersions.FirstOrDefault(v => v.Version == apiVersion); if (info == null) throw new UnknownApiVersion(apiVersion); var paths = GetApiDescriptionsFor(apiVersion) .Where(apiDesc => !(_options.IgnoreObsoleteActions && apiDesc.IsObsolete())) .OrderBy(_options.GroupNameSelector, _options.GroupNameComparer) .GroupBy(apiDesc => apiDesc.RelativePathSansQueryString()) .ToDictionary(group => "/" + group.Key, group => CreatePathItem(group, schemaRegistry)); var swaggerDoc = new SwaggerDocument { Info = info, Host = host, BasePath = basePath, Schemes = schemes, Paths = paths, Definitions = schemaRegistry.Definitions, SecurityDefinitions = _options.SecurityDefinitions }; var filterContext = new DocumentFilterContext( _apiDescriptionsProvider.ApiDescriptionGroups, null); foreach (var filter in _options.DocumentFilters) { filter.Apply(swaggerDoc, filterContext); } return swaggerDoc; }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { var setting = Its.Configuration.Settings.Get<SwaggerToolSettings>(); foreach (var apiDescription in apiExplorer.ApiDescriptions) { //hide attr //remove from docs autogenerated services if (setting.HideAbpAutogeneratedApi) { Regex r = new Regex(AbpPath); if (r.IsMatch(apiDescription.ID)) { swaggerDoc.paths.Remove("/" + apiDescription.RelativePath.Split('?')[0]); continue; } } if (setting.HideDocPaths!=null&&setting.HideDocPaths.Length>0) { if (setting.HideDocPaths.Where(p=>apiDescription.ID.Contains(p)).Count()>0) { swaggerDoc.paths.Remove("/" + apiDescription.RelativePath.Split('?')[0]); continue; } } if (!string.IsNullOrEmpty(setting.HideDocPathAttributeName)) { var attr = apiDescription.GetControllerAndActionAttributes<object>(); if (attr!=null&& attr.Where(p=>p.ToString()==setting.HideDocPathAttributeName).Count()>0) { swaggerDoc.paths.Remove("/" + apiDescription.RelativePath.Split('?')[0]); continue; } } } }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { var defaultApiKey = _settingManager.GetValue("Swashbuckle.DefaultApiKey", string.Empty); swaggerDoc.info.description = string.Format(CultureInfo.InvariantCulture, "For this sample, you can use the `{0}` key to satisfy the authorization filters.", defaultApiKey); swaggerDoc.info.termsOfService = ""; swaggerDoc.info.contact = new Contact { email = "*****@*****.**", name = "Virto Commerce", url = "http://virtocommerce.com" }; swaggerDoc.info.license = new License { name = "Virto Commerce Open Software License 3.0", url = "http://virtocommerce.com/opensourcelicense" }; var tags = _moduleCatalog.Modules .OfType<ManifestModuleInfo>() .Select(x => new Tag { name = x.Title, description = x.Description }) .ToList(); tags.Add(new Tag { name = "VirtoCommerce platform", description = "Platform functionality represent common resources and operations" }); swaggerDoc.tags = tags; }
/// <summary> /// Called when genrating the document /// </summary> public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) { swaggerDoc.BasePath = null; }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { var usertTokenSecurity = new Dictionary<string, IEnumerable<string>>(); usertTokenSecurity[SwaggerConfig.UserTokenSecurityDefinitionName] = new List<string>(); swaggerDoc.security = new List<IDictionary<string, IEnumerable<string>>>() {usertTokenSecurity}; }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.definitions["Object"].vendorExtensions["additionalProperties"] = true; }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.paths["/api/v{version}/error"].post = null; }
/// <summary> /// Initialize the document of Swagger model. /// </summary> protected virtual void InitializeDocument() { SwaggerDoc = new SwaggerDocument { info = new Info { title = "OData Service", description = "The OData Service at " + MetadataUri, version = "0.1.0" }, host = Host, schemes = new List<string> { "http" }, basePath = BasePath, consumes = new List<string> { "application/json" }, produces = new List<string> { "application/json" } }; }
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) { swaggerDoc.Extensions.Add("X-property1", "value"); }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.vendorExtensions.Add("x-document", "foo"); }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.tags = new List<Tag> { new Tag { name = "SharedModels", description = "A resource shared between OData and WebApi controllers" } }; }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.host = "foo"; }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { // Change host to be UI swaggerDoc.host = UrlHelper.TrimProtocol(ApplicationConfiguration.UrlUI); // Remove private API calls from live docs if (ApplicationConfiguration.IsEnvironmentLive) { var omitedControllers = new List<string> { "Home", "Log", "StaticReports", "PdfReporting", "NonPublicServices" }; foreach (var apiDescription in apiExplorer.ApiDescriptions) { if (omitedControllers.Contains(apiDescription.ActionDescriptor.ControllerDescriptor.ControllerName)) { var route = "/" + apiDescription.Route.RouteTemplate.TrimEnd('/'); swaggerDoc.paths.Remove(route); } } } }