-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Document Processors and Operation Processors
Document and operation processors are used to transform a Swagger document or Swagger operation after they have been generated.
See also Schema Processors.
Custom processors can be added with the settings object, e.g.
settings.OperationProcessors.Add(new MyProcessor());
The document processors are executed after the Swagger document has been completely generated. Operation processors are specified on the Swagger generator settings or as command parameters.
public class MyDocumentProcessor : IDocumentProcessor
{
public async Task ProcessAsync(DocumentProcessorContext context)
{
// TODO: Process context.Document
}
}
public class MyDocumentProcessor : IDocumentProcessor
{
public async Task ProcessAsync(DocumentProcessorContext context)
{
var assembly = GetType().GetTypeInfo().Assembly;
var types = assembly.ExportedTypes
.Where(t => t.FullName.StartsWith("MyNamespace.") && t.GetTypeInfo().IsClass);
foreach (var type in types)
{
if (!context.SchemaResolver.HasSchema(type, false))
{
await context.SchemaGenerator.GenerateAsync(type, null, context.SchemaResolver);
}
}
}
}
Execution order:
- All operations from
settings.OperationProcessors
(contains the default processors which generate parameters, responses, etc.) -
SwaggerOperationProcessorAttribute
on controller class -
SwaggerOperationProcessorAttribute
on operation method
Important: If you want to filter out some operations, insert the operation processor at index 0 (i.e. settings.OperationProcessors.Insert(0, new MyOperationProcessor())
) so that no unnecessary DTO schemas are generated.
To implement a custom operation processor, just create a class which implements the interface IOperationProcessor
:
public class MyOperationProcessor : IOperationProcessor
{
public async Task<bool> ProcessAsync(OperationProcessorContext context)
{
// TODO: Process context.Document
return true; // return false to exclude the operation from the document
}
}
You can register the custom IOperationProcessor
to transform each operation:
app.UseSwagger(typeof(Startup).Assembly, settings =>
settings.GeneratorSettings.OperationProcessors.Add(new MyOperationProcessor())
);
You can also specify a operation processor for a single operation:
[SwaggerOperationProcessor(typeof(MyOperationProcessor))]
public void MyOperation()
{
}
For better usability of this construct, you can now implement your own attribute:
public class MyOperationProcessorAttribute : SwaggerOperationProcessorAttribute
{
public MyOperationProcessorAttribute(string param1)
: base(typeof(MyOperationProcessor), param1)
{
}
}
// usage:
[MyOperationProcessor("Foo")]
public void MyOperation()
{
}