OpenAPISpec + Productivity

- 2 mins

Introduction

This blog talks about how to use Swashbuckle to enable using swagger.json creation and swagger UI creation in .NET Core 3.1 services. NOTE:

OpenAPI Specification

Benefits of adding swagger/OpenApiSpecs

Working demo:

Steps:

  1. Install Swashbuckle.AspNetCore (use > 5.0.0 since it supports OpenApi)
  2. In Startup.cs enable swagger by adding following in ConfigureServices
         services.AddSwaggerGen(setupAction =>
             {
                 setupAction.SwaggerDoc("<PathToHostSwagger>", new Microsoft.OpenApi.Models.OpenApiInfo
                 {
                     Title = "Your preferred title.",
                     Version = "1.0",
                 });
             });
    
    
  3. In Startup.cs also add following to Configure after app.UseHttpsRedirection()
         app.UseSwagger(c =>
             {
                 c.SerializeAsV2 = true; // Can use when intention is to create OpenAPISpec 2.0
             });
    
  4. With above code, you are enabling swagger file creation for your service and to be hosted at ‘/swagger//swagger.json`.
  5. The title and version is that for the swagger file that would be created.
  6. Enable Swagger UI by adding following in Configure function after the above added snippet.
    
             app.UseSwaggerUI(setupAction=>
             {
                 setupAction.SwaggerEndpoint("/swagger/"<PathToHostSwagger>/swagger.json", "<DfinitionName>");
             });
    
  7. Note: the SwaggerEndpoint defined above is same where the swagger.json file got hosted on creation i.e., /swagger/"<PathToHostSwagger>/swagger.json
  8. The UI looks like UI
rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora