Is it possible to define a common route parameter that can be set at the top of document, and if used it is injected in all the required routes?
We have a set of routes that all share a common route value
i.e. ~/user/{userId:guid}/....
Is it possible to setup the swagger document in such a way that there is a global user id field that when set applies its value to each route that has a /{userId:guid}/
segment?
So that when you are using the UI you don't have to manually copy the user id into each operation?
Is it possible to define a common route parameter that can be set at the top of document, and if used it is injected in all the required routes?
We have a set of routes that all share a common route value
i.e. ~/user/{userId:guid}/....
Is it possible to setup the swagger document in such a way that there is a global user id field that when set applies its value to each route that has a /{userId:guid}/
segment?
So that when you are using the UI you don't have to manually copy the user id into each operation?
1 Answer
Reset to default 0Yes, you can use IOperationFilter in Swagger to add a global route parameter. I’ve done something similar for API keys by setting them as required headers, and you can use the same approach for route parameters.
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace ApiKeyImplementation.Helpers
{
public class CustomHeaderSwaggerAttribute : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
operation.Parameters = new List<OpenApiParameter>();
operation.Parameters.Add(new OpenApiParameter
{
Name = VarHelper.KeyTypes.ApiKey.ToString(), //Add Key Name
In = ParameterLocation.Header, //Set Location
Required = true,
Description = "Add description if necessary",
Schema = new OpenApiSchema
{
Type = "string"
}
});
//If your application requires AppId as part of authentication
operation.Parameters.Add(new OpenApiParameter
{
Name = VarHelper.KeyTypes.AppId.ToString(),
In = ParameterLocation.Header,
Required = true,
Schema = new OpenApiSchema
{
Type = "string"
}
});
}
}
}
In your case, your will need to change the
In = ParameterLocation.Header => In = ParameterLocation.Path
Then register the filter in your program.cs
builder.Services.AddSwaggerGen(config =>
{
// Add Operation filter for header
config.OperationFilter<CustomHeaderSwaggerAttribute>();
});