Introduction
It can be very boring to manually write yaml description for swagger and maintain it especially when your WCF services are very simple. There is a nuget package called Swagger4WCF
that automatically generates yaml description for swagger 2.0 for each interface matching attributes used by WCF (ServiceContract
/OperationContract
/WebGet
/WebInvoke
).
How to Use Swagger4WCF
There are only a few step required to test it:
- Create a library with WCF interface:
[DataContract]
public class Book
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
}
[ServiceContract]
public interface IBookService
{
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
Book[] GetBooksList();
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
Book GetBookById(string id);
[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void AddBook(string name);
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void UpdateBook(string id, string name);
[OperationContract]
[WebInvoke(Method = "DELETE",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void DeleteBook(string id);
}
- Configure your project to generate documentation:
In properties of project > build tab > XML documentation file (do not specify path of documentation, it will provide default path that Swagger4WCF
looks for).
- Install nuget package on project where WCF interfaces are declared:
https://www.nuget.org/packages/Swagger4WCF
- Build your project will trigger
Swagger4WCF
:
You can see yaml in output directory!
Test the Generated yaml in Swagger Editor Online
Copy content of the generated yaml and Rendez vous to swagger online editor:
http://editor.swagger.io/#/
Clean swagger editor to get started:
Then paste the content of your generated yaml:
How It Works in the Background
Swagger4WCF
uses NuPack postbuild pattern to trigger at build time.
https://www.codeproject.com/Tips/1190360/How-to-setup-a-managed-postbuild-without-scripting
At build time, it will detect assemblies present in output directory, open them with mono.cecil
(to reflect assemblies) to generate expected yaml description for swagger 2.0.
Swagger4WCF
detects WebGet
/WebInvoke
to provide Verb
/Method
in serialization style in yaml.
Conclusion
Swagger4WCF
may help you to save time when developing web application. It is easy to test, use or remove. It can be a nice starter for a newbie in swagger technology because it is only required to install a nuget package. Unfortunately, it is not mature enough for advanced WCF configuration, but I'm sure it can be improved.