Open API 2.0 (AKA Swagger) is a de-facto standard to document Web API. For ASP.NET Web API applications, Swashbuckle helps developers build the Swagger definition a lot easier. As Swashbuckle hasn’t fully implemented the Swagger specification, we need to develop some extensions using a few interfaces provided by Swashbuckle. In this post we’re going to talk about a couple of extensions to make Swagger definition more completed.
The sample codes used in this post can be found here.
Acknowledgement
The sample application uses the following spec:
Defining
and in Operation Object
In Swagger, HTTP verb like. Each Operation Object can define which content types are to be requested ( ) and which content types are to be returned ( ). Therefore, with Swashbuckle, Swagger document page produces like:
, , , or is referred as
In other words, Swashbuckle assumes those five content types as default for requests –
, , , , and . And those four content types are the default response ones – , , and . Here’s a part of the Swagger definition automatically generated.
If we want to globally apply those content types, that can be done within the global configuration. Here’s the sample OWIN configuration:
It clears everything and add only one content type –
. By doing so, we can globally set one content type for both requests and responses. If we want to have more control on each endpoint, the interface of Swashbuckle gives us that flexibility.Implementing
Decorator
First of all, we need to write a simple decorator, called
which handles the field of the Operation Object.
Through this decorator, we simply define number of content types to pass. How does it apply?
Let’s move on.
Implementing
Filter
We now write the
filter class by implementing the interface like.
What it does are:
- To check the content type values passed from the decorator, and
- To add all content types passed from the decorator to .
This needs to be added to the Swashbuckle configuration like:
Now run the Web API again and we’ll see the result like:

Implementing
and
Both
decorator and filter can be written as what we did above for .
The
decorator can be applied to:
The picture below is the Swagger definition based on the extensions above:

We’ve so far had a look how to extend Swashbuckle to fill the missing parts in Swagger definition. In the next post, we’ll walk through another extension for Swagger definition.
SWASHBUCKLE PRO TIPS FOR ASP.NET WEB API – CONTENT TYPES
Reviewed by MOZ FAMOUS
on
abril 19, 2018
Rating:
Nenhum comentário: