Created
September 8, 2022 09:28
-
-
Save JacopoWolf/120ea738ca830d46f7e3307e948a90bc to your computer and use it in GitHub Desktop.
ASP.NET OpenApi SwaggerUI default version
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// inspired by https://stackoverflow.com/questions/69899771/add-default-value-to-swagger-path-parameters | |
// this filter adds the latest controller or action version to the swagger ui parameters | |
// so when [Route("api/v{version:apiVersion}/[controller]")] | |
// in swaggerUI the version will be an additional required parameter to fill in. | |
// This filter will add a default value for the latest | |
internal class ApiVersionRouteParameterOperationFilter : IOperationFilter | |
{ | |
internal static IEnumerable<T> GetControllerAndActionAttributes<T>( OperationFilterContext context ) where T : Attribute | |
{ | |
var controllerAttributes = context.MethodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes<T>(); | |
var actionAttributes = context.MethodInfo.GetCustomAttributes<T>(); | |
return controllerAttributes.Concat(actionAttributes); | |
} | |
public void Apply( OpenApiOperation operation, OperationFilterContext context ) | |
{ | |
var parameter = operation.Parameters.FirstOrDefault(p => | |
p.In == ParameterLocation.Path && p.Name.Equals(VERSION_ROUTE_NAME)); | |
if (parameter is null) | |
return; | |
var apiattrs = GetControllerAndActionAttributes<ApiVersionAttribute>(context); | |
parameter.Schema.Default = new OpenApiString(apiattrs.Max(a => a.Versions.Single()).ToString()); | |
parameter.Description += "\nexplicit versions:" + string.Join(';',apiattrs.Select(a => a.Versions.Single())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment