4

I am generating Swagger document for my .Net core 6 based API. I have some error models which will be returned by my Gateway. These are not used/returned in any of my API endpoints. I want to add these models to Swagger document schema collection. I am able to successfully add them if I follow inline way. Is there a way to include existing models in Swagger schema collection?

I also want to include webhook models and examples to schemas collection without going through inline option.

Thanks for your time.

2
  • can put any example which model you want to add to schema ? Commented Aug 1, 2022 at 8:35
  • @CodingMytra - thank you for your comment. I have created a model (ex: GWErrorModel.cs) like below. I want to inject this into schema collection, so that I can refer it in all responses of all my endpoints. public class GWErrorModel { public string status { get; set; } public string errorMessage { get; set; } } Commented Aug 1, 2022 at 13:23

1 Answer 1

6

You can do following to add the model to schema collection.

Create a custom document filter

public class CustomDocumentFilter : IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { context.SchemaGenerator.GenerateSchema(typeof(GWErrorModel), context.SchemaRepository); } } 

add it to program.cs

 builder.Services.AddSwaggerGen(o => { o.DocumentFilter<CustomDocumentFilter>(); }); 

you will see the model is added to schema collection.

enter image description here

Hope it helps.

Sign up to request clarification or add additional context in comments.

4 Comments

Wonderful. Thank you so much for the answer, sample code and your time.
Perfect, worked great in .Net 6 for me
This seems to no longer work in .NET 8. The signature of the Apply meethod has changed and it's not clear how to achieve this with the new schema.
@Konstantin, which version of swashbuckle are you talking about. I can see still same definition of Apply method in IDocumentFilter

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.