Skip to content

Instantly share code, notes, and snippets.

@JacopoWolf
Created September 8, 2022 09:28
Show Gist options
  • Save JacopoWolf/120ea738ca830d46f7e3307e948a90bc to your computer and use it in GitHub Desktop.
Save JacopoWolf/120ea738ca830d46f7e3307e948a90bc to your computer and use it in GitHub Desktop.
ASP.NET OpenApi SwaggerUI default version
// 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