private void AddControllerNameTag(OperationProcessorContext context) { var controllerName = context.MethodInfo.DeclaringType.Name; if (controllerName.EndsWith("Controller")) controllerName = controllerName.Substring(0, controllerName.Length - 10); context.OperationDescription.Operation.Tags.Add(controllerName); }
/// <summary>Processes the specified method information.</summary> /// <param name="context"></param> /// <returns>true if the operation should be added to the Swagger specification.</returns> public bool Process(OperationProcessorContext context) { ProcessSwaggerTagsAttribute(context.Document, context.OperationDescription, context.MethodInfo); ProcessSwaggerTagAttributes(context.Document, context.OperationDescription, context.MethodInfo); if (!context.OperationDescription.Operation.Tags.Any()) AddControllerNameTag(context); return true; }
/// <summary>Processes the specified method information.</summary> /// <param name="context"></param> /// <returns>true if the operation should be added to the Swagger specification.</returns> public bool Process(OperationProcessorContext context) { if (context.OperationDescription.Operation.Security == null) context.OperationDescription.Operation.Security = new List<SwaggerSecurityRequirement>(); var scopes = GetScopes(context.OperationDescription, context.MethodInfo); context.OperationDescription.Operation.Security.Add(new SwaggerSecurityRequirement { { _name, scopes } }); return true; }
private async Task AddBodyParameterAsync(OperationProcessorContext context, string name, ParameterInfo parameter) { var operation = context.OperationDescription.Operation; if (parameter.ParameterType.Name == "XmlDocument" || parameter.ParameterType.InheritsFrom("XmlDocument", TypeNameStyle.Name)) { operation.Consumes = new List <string> { "application/xml" }; operation.Parameters.Add(new SwaggerParameter { Name = name, Kind = SwaggerParameterKind.Body, Schema = new JsonSchema4 { Type = JsonObjectType.String }, IsNullableRaw = true, IsRequired = parameter.HasDefaultValue == false, Description = await parameter.GetDescriptionAsync(parameter.GetCustomAttributes()).ConfigureAwait(false) }); } else if (parameter.ParameterType.IsAssignableTo("System.IO.Stream", TypeNameStyle.FullName)) { operation.Consumes = new List <string> { "application/octet-stream" }; operation.Parameters.Add(new SwaggerParameter { Name = name, Kind = SwaggerParameterKind.Body, Schema = new JsonSchema4 { Type = JsonObjectType.String, Format = JsonFormatStrings.Byte }, IsNullableRaw = true, IsRequired = parameter.HasDefaultValue == false, Description = await parameter.GetDescriptionAsync(parameter.GetCustomAttributes()).ConfigureAwait(false) }); } else { var operationParameter = await context.SwaggerGenerator .CreateBodyParameterAsync(name, parameter).ConfigureAwait(false); operation.Parameters.Add(operationParameter); } }
private OpenApiParameter TryAddFileParameter( OperationProcessorContext context, JsonTypeDescription typeInfo, ContextualParameterInfo contextualParameter) { var isFileArray = IsFileArray(contextualParameter.Type, typeInfo); var hasSwaggerFileAttribute = contextualParameter.Attributes .FirstAssignableToTypeNameOrDefault("SwaggerFileAttribute", TypeNameStyle.Name) != null; if (typeInfo.Type == JsonObjectType.File || typeInfo.Format == JsonFormatStrings.Binary || hasSwaggerFileAttribute || isFileArray) { return(AddFileParameter(context, contextualParameter, isFileArray)); } return(null); }
public bool Process(OperationProcessorContext context) { var requestExample = ((IExampleProvider?)Activator.CreateInstance(_requestExampleType)) !.GetExample(); var operationBody = context.OperationDescription.Operation.RequestBody; foreach (var bodyType in operationBody.Content.Values) { bodyType.Example = JsonConvert.SerializeObject(requestExample, JsonSerializerSettings); } var responseExample = ((IExampleProvider?)Activator.CreateInstance(_responseExampleType)) !.GetExample(); var operationResponse = context.OperationDescription.Operation.ActualResponses["200"]; operationResponse.Examples = JsonConvert.SerializeObject(responseExample, JsonSerializerSettings); return(true); }
public Task <bool> ProcessAsync(OperationProcessorContext context) { var groupName = context.ControllerType.GetCustomAttribute <ApiExplorerSettingsAttribute>()?.GroupName; if (!string.IsNullOrWhiteSpace(groupName)) { context.OperationDescription.Operation.Tags = new List <string> { groupName }; return(TaskHelper.True); } else { return(TaskHelper.False); } }
private void ProcessDescription(OperationProcessorContext context, List <Attribute> attributes) { dynamic openApiOperationAttribute = attributes .SingleOrDefault(a => a.GetType().Name == "OpenApiOperationAttribute"); string description = openApiOperationAttribute?.Description; if (string.IsNullOrEmpty(description)) { description = context.MethodInfo.GetXmlDocsRemarks(); } if (!string.IsNullOrEmpty(description)) { context.OperationDescription.Operation.Description = description; } }
/// <inheritdoc/> public bool Process(OperationProcessorContext context) { var responses = context.OperationDescription.Operation.Responses; foreach (var(httpStatusCode, res) in responses) { if (!string.IsNullOrEmpty(res.Description)) { continue; } if (defaultDescriptionMap.ContainsKey(httpStatusCode)) { res.Description = defaultDescriptionMap[httpStatusCode]; } } return(true); }
private void TryAddRequestHeader(OperationProcessorContext context, string name, string description) { var existingHeader = context.OperationDescription.Operation.Parameters.FirstOrDefault( x => x.Kind == OpenApiParameterKind.Header && x.Name.Equals(name, StringComparison.Ordinal)); if (existingHeader == null) { context.OperationDescription.Operation.Parameters.Add(new OpenApiParameter { Name = name, Description = description, Kind = OpenApiParameterKind.Header, Schema = new JsonSchema { Type = JsonObjectType.String }, }); } }
public Task <bool> ProcessAsync(OperationProcessorContext context) { var operation = context.OperationDescription.Operation; var descriptionAttribute = context.MethodInfo.GetCustomAttribute(typeof(DescriptionAttribute)); if (descriptionAttribute != null) { operation.Description = (descriptionAttribute as DescriptionAttribute).Description; } operation.OperationId = operation.OperationId.Split("_").Last(); operation.Summary = operation.OperationId.Humanize(LetterCasing.Title); return(Task.FromResult(true)); }
private async Task <SwaggerParameter> CreatePrimitiveParameterAsync( OperationProcessorContext context, ExtendedApiParameterDescription extendedApiParameter) { var operationParameter = await context.SwaggerGenerator.CreatePrimitiveParameterAsync( extendedApiParameter.ApiParameter.Name, await extendedApiParameter.GetDocumentationAsync().ConfigureAwait(false), extendedApiParameter.ParameterType, extendedApiParameter.Attributes).ConfigureAwait(false); if (extendedApiParameter.ParameterInfo?.HasDefaultValue == true) { operationParameter.Default = extendedApiParameter.ParameterInfo.DefaultValue; } operationParameter.IsRequired = extendedApiParameter.IsRequired(_settings.RequireParametersWithoutDefault); return(operationParameter); }
private static async Task AddInternalErrorResponseAsync(OperationProcessorContext context, SwaggerOperation operation) { if (operation.Responses.ContainsKey("500")) { return; } var errorType = typeof(ErrorDto); var errorSchema = JsonObjectTypeDescription.FromType(errorType, new Attribute[0], EnumHandling.String); var response = new SwaggerResponse { Description = "Operation failed." }; response.Schema = await context.SwaggerGenerator.GenerateAndAppendSchemaFromTypeAsync(errorType, errorSchema.IsNullable, null); operation.Responses.Add("500", response); }
public Task <bool> ProcessAsync(OperationProcessorContext context) { var versionAttributes = context.MethodInfo.GetCustomAttributes() .Concat(context.MethodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes()) .Where(a => a.GetType().IsAssignableTo("MapToApiVersionAttribute", TypeNameStyle.Name) || a.GetType().IsAssignableTo("ApiVersionAttribute", TypeNameStyle.Name)) .Select(a => (dynamic)a) .ToArray(); var versionAttribute = versionAttributes.FirstOrDefault(); if (ObjectExtensions.HasProperty(versionAttribute, "Versions")) { ReplaceApiVersionInPath(context.OperationDescription, versionAttribute.Versions); } return(Task.FromResult(true)); }
private async Task <SwaggerParameter> TryAddFileParameterAsync( OperationProcessorContext context, JsonTypeDescription info, ParameterInfo parameter) { var isFileArray = IsFileArray(parameter.ParameterType, info); var attributes = parameter.GetCustomAttributes() .Union(parameter.ParameterType.GetTypeInfo().GetCustomAttributes()); var hasSwaggerFileAttribute = attributes.Any(a => a.GetType().IsAssignableTo("SwaggerFileAttribute", TypeNameStyle.Name)); if (info.Type == JsonObjectType.File || hasSwaggerFileAttribute || isFileArray) { return(await AddFileParameterAsync(context, parameter, isFileArray).ConfigureAwait(false)); } return(null); }
public bool Process(OperationProcessorContext context) { var responseTypeAttributes = context.MethodInfo.GetCustomAttributes() .Where(a => a.GetType().Name == "ResponseTypeAttribute" || a.GetType().Name == "SwaggerResponseAttribute") .ToList(); var producesResponseTypeAttributes = context.MethodInfo.GetCustomAttributes() .Where(a => a.GetType().Name == "ProducesResponseTypeAttribute" || a.GetType().Name == "ProducesAttribute") .ToList(); var attributes = responseTypeAttributes.Concat(producesResponseTypeAttributes); ProcessResponseTypeAttributes(context, attributes); return(true); }
/// <inheritdoc /> public bool Process(OperationProcessorContext context) { context.OperationDescription.Operation.Security ??= new List <OpenApiSecurityRequirement>(); OpenApiSecurityRequirement perms = context.MethodInfo.GetCustomAttributes <UserOnlyAttribute>() .Aggregate(new OpenApiSecurityRequirement(), (agg, cur) => { agg[nameof(Kyoo)] = Array.Empty <string>(); return(agg); }); perms = context.MethodInfo.GetCustomAttributes <PermissionAttribute>() .Aggregate(perms, (agg, cur) => { ICollection <string> permissions = _GetPermissionsList(agg, cur.Group); permissions.Add($"{cur.Type}.{cur.Kind.ToString().ToLower()}"); agg[nameof(Kyoo)] = permissions; return(agg); }); PartialPermissionAttribute controller = context.ControllerType .GetCustomAttribute <PartialPermissionAttribute>(); if (controller != null) { perms = context.MethodInfo.GetCustomAttributes <PartialPermissionAttribute>() .Aggregate(perms, (agg, cur) => { Group group = controller.Group != Group.Overall ? controller.Group : cur.Group; string type = controller.Type ?? cur.Type; Kind kind = controller.Type == null ? controller.Kind : cur.Kind; ICollection <string> permissions = _GetPermissionsList(agg, group); permissions.Add($"{type}.{kind.ToString().ToLower()}"); agg[nameof(Kyoo)] = permissions; return(agg); }); } context.OperationDescription.Operation.Security.Add(perms); return(true); }
/// <summary> /// Process OpenApi document and remove parameters with Parameter Name 'version' /// </summary> /// <returns>true if any matching parameters found, false if not</returns> public bool Process(OperationProcessorContext context) { var operationDescription = context.OperationDescription; var versionParameter = operationDescription.Operation.Parameters.Where(p => p.Name == "version").ToList(); if (versionParameter.Any()) { foreach (var parameter in versionParameter) { context.OperationDescription.Operation.Parameters.Remove(parameter); } return(true); } else { return(false); } }
/// <summary> /// Processes the specified method information. /// </summary> /// <param name="context">The processor context.</param> /// <returns>true if the operation should be added to the Swagger specification.</returns> public bool Process(OperationProcessorContext context) { var operation = context.OperationDescription.Operation; if (operation.ExtensionData == null) { operation.ExtensionData = new Dictionary <string, object>(); } foreach (var extensionDataAttribute in from extensionDataAttribute in context.MethodInfo.GetCustomAttributes() .GetAssignableToTypeName("SwaggerExtensionDataAttribute", TypeNameStyle.Name) select(dynamic) extensionDataAttribute) { string key = extensionDataAttribute.Key; string value = extensionDataAttribute.Value; operation.ExtensionData[key] = value; } foreach (var parameter in context.Parameters) { if (parameter.Value.ExtensionData == null) { parameter.Value.ExtensionData = new Dictionary <string, object>(); } foreach (var extensionDataAttribute in from extensionDataAttribute in parameter.Key.GetCustomAttributes(true) .GetAssignableToTypeName("SwaggerExtensionDataAttribute", TypeNameStyle.Name) select(dynamic) extensionDataAttribute) { string key = extensionDataAttribute.Key; string value = extensionDataAttribute.Value; parameter.Value.ExtensionData[key] = value; } } return(true); }
public bool Process(OperationProcessorContext context) { if (context.OperationDescription.Path == supportedPath) { var operation = context.OperationDescription.Operation; if (supportSearch) { operation.AddQueryParameter("$search", JsonObjectType.String, "Optional OData full text search."); } operation.AddQueryParameter("$top", JsonObjectType.Number, $"Optional number of {entity} to take."); operation.AddQueryParameter("$skip", JsonObjectType.Number, $"Optional number of {entity} to skip."); operation.AddQueryParameter("$orderby", JsonObjectType.String, "Optional OData order definition."); operation.AddQueryParameter("$filter", JsonObjectType.String, "Optional OData filter definition."); } return(true); }
public bool Process(OperationProcessorContext context) { var data = context.OperationDescription.Operation.Parameters; var schema = JsonSchema.FromType <CreateESignRequest>(); data.Add(new OpenApiParameter() { Name = "CreateESignRequest", IsRequired = true, Kind = OpenApiParameterKind.FormData, Schema = schema }); data.Add(new OpenApiParameter() { Name = "Document1", IsRequired = true, Kind = OpenApiParameterKind.FormData, Type = JsonObjectType.File, Description = "The first document" }); data.Add(new OpenApiParameter() { Name = "Document2", IsRequired = false, Kind = OpenApiParameterKind.FormData, Type = JsonObjectType.File, Description = "The second document" }); data.Add(new OpenApiParameter() { Name = "Document[n]", IsRequired = false, Kind = OpenApiParameterKind.FormData, Type = JsonObjectType.File, Description = "The n-th document" }); return(true); }
private async Task AddFileParameterAsync(OperationProcessorContext context, ExtendedApiParameterDescription extendedApiParameter, bool isFileArray) { var parameterDocumentation = string.Empty; if (extendedApiParameter.ParameterInfo != null) { parameterDocumentation = await extendedApiParameter.ParameterInfo.GetDescriptionAsync(extendedApiParameter.Attributes).ConfigureAwait(false); } else if (extendedApiParameter.PropertyInfo != null) { parameterDocumentation = await extendedApiParameter.PropertyInfo.GetDescriptionAsync(extendedApiParameter.Attributes).ConfigureAwait(false); } var operationParameter = await CreatePrimitiveParameterAsync( context, extendedApiParameter).ConfigureAwait(false); InitializeFileParameter(operationParameter, isFileArray); context.OperationDescription.Operation.Parameters.Add(operationParameter); }
/// <summary>Processes the specified method information.</summary> /// <param name="context"></param> /// <returns>true if the operation should be added to the Swagger specification.</returns> public bool Process(OperationProcessorContext context) { var securityRequirement = GetSecurityRequirement(context.MethodInfo); if (securityRequirement) { if (context.OperationDescription.Operation.Security == null) { context.OperationDescription.Operation.Security = new Collection <OpenApiSecurityRequirement>(); } context.OperationDescription.Operation.Security.Add(new OpenApiSecurityRequirement() { { _name, new string[] { } } }); } return(true); }
/// <summary>Processes the specified method information.</summary> /// <param name="context"></param> /// <returns>true if the operation should be added to the Swagger specification.</returns> public async Task <bool> ProcessAsync(OperationProcessorContext context) { var responseTypeAttributes = context.MethodInfo.GetCustomAttributes() .Where(a => a.GetType().Name == "ResponseTypeAttribute" || a.GetType().Name == "SwaggerResponseAttribute") .Concat(context.MethodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes() .Where(a => a.GetType().Name == "SwaggerResponseAttribute")) .ToList(); var producesResponseTypeAttributes = context.MethodInfo.GetCustomAttributes() .Where(a => a.GetType().Name == "ProducesResponseTypeAttribute") .ToList(); var parameter = context.MethodInfo.ReturnParameter; var attributes = responseTypeAttributes.Concat(producesResponseTypeAttributes); await ProcessResponseTypeAttributes(context, parameter, attributes); return(true); }
public bool Process(OperationProcessorContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } context.OperationDescription.Operation.Parameters.Add( new NSwag.OpenApiParameter { Name = "x-request-id", Kind = NSwag.OpenApiParameterKind.Header, Type = NJsonSchema.JsonObjectType.String, IsRequired = false, Description = "Request id. request with duplicate x-request-id will be ignored.", Style = NSwag.OpenApiParameterStyle.Simple }); return(true); }
public Task <bool> ProcessAsync(OperationProcessorContext context) { var anonymous = context.ControllerType.GetCustomAttribute <AllowAnonymousAttribute>() ?? context.MethodInfo.GetCustomAttribute <AllowAnonymousAttribute>(); if (anonymous != null) { return(Task.FromResult(true)); } context.OperationDescription.Operation.Responses.Add( new KeyValuePair <string, SwaggerResponse>( "401", new SwaggerResponse { Description = HttpStatusCode.Unauthorized.ToString(), })); return(Task.FromResult(true)); }
/// <summary>Processes the specified method information.</summary> /// <param name="context"></param> /// <returns>true if the operation should be added to the Swagger specification.</returns> public bool Process(OperationProcessorContext context) { ProcessSwaggerTagsAttribute(context.Document, context.OperationDescription, context.MethodInfo); ProcessSwaggerTagAttributes(context.Document, context.OperationDescription, context.MethodInfo); if (!context.OperationDescription.Operation.Tags.Any()) { var typeInfo = context.ControllerType.GetTypeInfo(); ProcessControllerSwaggerTagsAttribute(context.OperationDescription, typeInfo); ProcessControllerSwaggerTagAttributes(context.OperationDescription, typeInfo); } if (!context.OperationDescription.Operation.Tags.Any()) { AddControllerNameTag(context); } return(true); }
/// <summary>Processes the specified method information.</summary> /// <param name="context"></param> /// <returns>true if the operation should be added to the Swagger specification.</returns> public bool Process(OperationProcessorContext context) { dynamic descriptionAttribute = context.MethodInfo.GetCustomAttributes() .SingleOrDefault(a => a.GetType().Name == "DescriptionAttribute"); if (descriptionAttribute != null) context.OperationDescription.Operation.Summary = descriptionAttribute.Description; else { var summary = context.MethodInfo.GetXmlSummary(); if (summary != string.Empty) context.OperationDescription.Operation.Summary = summary; } var remarks = context.MethodInfo.GetXmlRemarks(); if (remarks != string.Empty) context.OperationDescription.Operation.Description = remarks; return true; }
public bool Process(OperationProcessorContext context) { var parameterInfos = context.MethodInfo.GetParameters(); var parameterInfo = parameterInfos.SingleOrDefault(); if (parameterInfo == null) { return(false); } var isQuery = context.MethodInfo.DeclaringType.IsAssignableToGenericType(typeof(IQueryRequestHandler <,>)); if (isQuery) { // Query foreach (var contextualProperty in parameterInfo.ToContextualParameter().Type.GetContextualProperties()) { var operationParameter = context.DocumentGenerator.CreatePrimitiveParameter(contextualProperty.Name, contextualProperty.Name, contextualProperty); operationParameter.Kind = OpenApiParameterKind.Query; context.OperationDescription.Operation.Parameters.Add(operationParameter); } } else { // Command var operationParameter = new OpenApiParameter { Kind = OpenApiParameterKind.Body, Name = parameterInfo.Name, Description = parameterInfo.Name, Schema = context.SchemaGenerator.GenerateWithReferenceAndNullability <JsonSchema>(parameterInfo.ParameterType.ToContextualType(), true, context.SchemaResolver), Position = 1 }; context.OperationDescription.Operation.Parameters.Add(operationParameter); ((Dictionary <ParameterInfo, OpenApiParameter>)context.Parameters)[parameterInfo] = operationParameter; } return(true); }
private string GetHigherActionApiVersion(OperationProcessorContext context) { // Try get highest api version defined at action level System.Attribute[] actionApiVersionAttributes = context.MethodInfo.GetCustomAttributes() .GetAssignableToTypeName("ApiVersionAttribute", TypeNameStyle.Name) .Where(a => a.HasProperty("Versions")) .ToArray(); if (actionApiVersionAttributes.Length > 0) { return(actionApiVersionAttributes.SelectMany((dynamic a) => ((IEnumerable)a.Versions).OfType <object>().Select(v => v.ToString())) .First()); } // Try get highest api version defined at controller level return(context.ControllerType.GetTypeInfo().GetCustomAttributes(true) .GetAssignableToTypeName("ApiVersionAttribute", TypeNameStyle.Name) .Where(a => a.HasProperty("Versions")) .SelectMany((dynamic a) => ((IEnumerable)a.Versions).OfType <object>().Select(v => v.ToString())) .FirstOrDefault()); }
/// <summary>Processes the specified method information.</summary> /// <param name="context"></param> /// <returns>true if the operation should be added to the Swagger specification.</returns> public bool Process(OperationProcessorContext context) { var responseTypeAttributes = context.MethodInfo.GetCustomAttributes() .Where(a => a.GetType().IsAssignableToTypeName("ResponseTypeAttribute", TypeNameStyle.Name) || a.GetType().IsAssignableToTypeName("SwaggerResponseAttribute", TypeNameStyle.Name)) .Concat(context.MethodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes() .Where(a => a.GetType().IsAssignableToTypeName("SwaggerResponseAttribute", TypeNameStyle.Name))) .ToList(); var producesResponseTypeAttributes = context.MethodInfo.GetCustomAttributes() .Where(a => a.GetType().IsAssignableToTypeName("ProducesResponseTypeAttribute", TypeNameStyle.Name) || a.GetType().IsAssignableToTypeName("ProducesAttribute", TypeNameStyle.Name)) .ToList(); var attributes = responseTypeAttributes.Concat(producesResponseTypeAttributes); ProcessResponseTypeAttributes(context, attributes); UpdateResponseDescription(context); return(true); }
/// <inheritdocs /> public override bool Process(OperationProcessorContext context) { #if NET6_0 var aspNetCoreContext = (AspNetCoreOperationProcessorContext)context; var tagsAttributes = aspNetCoreContext .ApiDescription? .ActionDescriptor? .EndpointMetadata? .OfType <TagsAttribute>(); if (tagsAttributes != null) { foreach (var tag in tagsAttributes.SelectMany(a => a.Tags)) { aspNetCoreContext.OperationDescription.Operation.Tags.Add(tag); } } #endif return(base.Process(context)); }
private void AddFileParameter(OperationProcessorContext context, ExtendedApiParameterDescription extendedApiParameter, bool isFileArray) { if (_settings.SchemaType == SchemaType.Swagger2) { var operationParameter = CreatePrimitiveParameter(context, extendedApiParameter); operationParameter.Type = JsonObjectType.File; operationParameter.Kind = OpenApiParameterKind.FormData; if (isFileArray) { operationParameter.CollectionFormat = OpenApiParameterCollectionFormat.Multi; } context.OperationDescription.Operation.Parameters.Add(operationParameter); } else { var schema = CreateOrGetFormDataSchema(context); schema.Properties[extendedApiParameter.ApiParameter.Name] = CreateFormDataProperty(context, extendedApiParameter, schema); } }
/// <summary>Adds the controller name as operation tag.</summary> /// <param name="context">The context.</param> protected override void AddControllerNameTag(OperationProcessorContext context) { var aspNetCoreContext = (AspNetCoreOperationProcessorContext)context; if (aspNetCoreContext.ControllerType.IsGenericType) { var controllerType = aspNetCoreContext.ControllerType.GetGenericTypeDefinition(); if (controllerType == typeof(GenericGetController <>) || controllerType == typeof(GenericPostController <>) || controllerType == typeof(GenericDeleteController <>)) { var entityType = aspNetCoreContext.ControllerType.GenericTypeArguments[0]; var customAttribute = entityType.GetCustomAttributes(typeof(ApiAttribute), true).FirstOrDefault() as ApiAttribute; var groupPrefix = customAttribute.ControllerRoutePrefix; aspNetCoreContext.OperationDescription.Operation.Tags.Add(groupPrefix); return; } } base.AddControllerNameTag(context); }
/// <summary>Processes the specified method information.</summary> /// <param name="context"></param> /// <returns>true if the operation should be added to the Swagger specification.</returns> public bool Process(OperationProcessorContext context) { var httpPath = context.OperationDescription.Path; var parameters = context.MethodInfo.GetParameters().ToList(); foreach (var parameter in parameters.Where(p => p.ParameterType != typeof(CancellationToken) && p.GetCustomAttributes().All(a => a.GetType().Name != "FromServicesAttribute") && p.GetCustomAttributes().All(a => a.GetType().Name != "BindNeverAttribute"))) { var nameLower = parameter.Name.ToLowerInvariant(); if (httpPath.ToLowerInvariant().Contains("{" + nameLower + "}") || httpPath.ToLowerInvariant().Contains("{" + nameLower + ":")) // path parameter { var operationParameter = context.SwaggerGenerator.CreatePrimitiveParameter(parameter.Name, parameter); operationParameter.Kind = SwaggerParameterKind.Path; operationParameter.IsNullableRaw = false; operationParameter.IsRequired = true; // Path is always required => property not needed context.OperationDescription.Operation.Parameters.Add(operationParameter); } else { var parameterInfo = JsonObjectTypeDescription.FromType(parameter.ParameterType, parameter.GetCustomAttributes(), _settings.DefaultEnumHandling); if (TryAddFileParameter(parameterInfo, context.OperationDescription.Operation, parameter, context.SwaggerGenerator) == false) { dynamic fromBodyAttribute = parameter.GetCustomAttributes() .SingleOrDefault(a => a.GetType().Name == "FromBodyAttribute"); dynamic fromUriAttribute = parameter.GetCustomAttributes() .SingleOrDefault(a => a.GetType().Name == "FromUriAttribute" || a.GetType().Name == "FromQueryAttribute"); var bodyParameterName = TryGetStringPropertyValue(fromBodyAttribute, "Name") ?? parameter.Name; var uriParameterName = TryGetStringPropertyValue(fromUriAttribute, "Name") ?? parameter.Name; if (parameterInfo.IsComplexType) { if (fromBodyAttribute != null || (fromUriAttribute == null && _settings.IsAspNetCore == false)) AddBodyParameter(bodyParameterName, parameter, context.OperationDescription.Operation, context.SwaggerGenerator); else AddPrimitiveParametersFromUri(uriParameterName, context.OperationDescription.Operation, parameter, parameterInfo, context.SwaggerGenerator); } else { if (fromBodyAttribute != null) AddBodyParameter(bodyParameterName, parameter, context.OperationDescription.Operation, context.SwaggerGenerator); else AddPrimitiveParameter(uriParameterName, context.OperationDescription.Operation, parameter, context.SwaggerGenerator); } } } } if (_settings.AddMissingPathParameters) { foreach (Match match in Regex.Matches(httpPath, "{(.*?)(:(([^/]*)?))?}")) { var parameterName = match.Groups[1].Value; if (context.OperationDescription.Operation.Parameters.All(p => !string.Equals(p.Name, parameterName, StringComparison.OrdinalIgnoreCase))) { var parameterType = match.Groups.Count == 5 ? match.Groups[3].Value : "string"; var operationParameter = context.SwaggerGenerator.CreatePathParameter(parameterName, parameterType); context.OperationDescription.Operation.Parameters.Add(operationParameter); } } } RemoveUnusedPathParameters(context.OperationDescription, httpPath); UpdateConsumedTypes(context.OperationDescription); EnsureSingleBodyParameter(context.OperationDescription); return true; }