Achraf Ben Alaya
No Result
View All Result
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
  • Cloud
  • Motivation
  • General Tips & Fix
  • Exam Preparation
    • AZ-104
    • AZ-400
  • About
    • Resume
SUBSCRIBE
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
  • Cloud
  • Motivation
  • General Tips & Fix
  • Exam Preparation
    • AZ-104
    • AZ-400
  • About
    • Resume
No Result
View All Result
Achraf Ben Alaya
No Result
View All Result
ADVERTISEMENT
Home Blog

Swagger & OpenAPI and Versioning for ASP.NET Core

achraf by achraf
December 8, 2020
in Blog, c#
4 min read
0
Swagger & OpenAPI and Versioning for ASP.NET Core
0
SHARES
1k
VIEWS
Share on FacebookShare on Twitter

Introduction

When you create a new .Netcore web API project ,you need to present and define in a very easy way to read .
In this case , Swagger is the solution .

Swagger is an Interface Description Language for describing RESTful APIs expressed using JSON. Swagger is used together with a set of open-source software tools to design, build, document, and use RESTful web services. Swagger includes automated documentation, code generation, and test-case generation.

Adding Swagger to a Web Api Core 3.1 project

You can add swagger to the project by installing the following NuGet package :

Swashbuckle.AspNetCore

Swagger Configuration

Sometimes configuring a nuget package can be hard and time wasting , but this not the case with swagger .

First we are going to  open Startup.cs and add Swagger service inside ConfigureServices

services.AddSwaggerGen(c =>
          {
              c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
          });

 

After that we are going to enable  Swagger in Configure() method :

 

app.UseSwagger();
         app.UseSwaggerUI(c => {

             c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");

         });

 

Now as I mentioned in the demo , we need to configure the launch browser in Debug from the properties of the solution :

 

Now, when we are going to start a new debugging session, we will be redirected to :

http://localhost:[yourportnumber]/swagger

Now , everything done if you are going to have one version of the API ,next we are going to see how to create different versions.

Versioning

When we update the API major version whenever we introduce breaking changes. Internally, we update minor and patch versions whenever we add functionality and backward-compatible updates. When we release a new major version of the an API clients can choose to either continue using an existing major version or migrate to the new one , so different versions must be present .

Changes that we need to do in Startup.cs :

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace swaggerytDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //Register the Swagger generator, defining 1 or more Swagger documents
            //services.AddSwaggerGen(c =>
            //{
            //    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
            //});

            services.AddControllers(options =>
            {
                options.Conventions.Add(new GroupingByNamespaceConvention());
            });

            services.AddSwaggerGen(config =>
            {
                var titlebase = "Ytdemo1";
                var desc = "Description";
                var termsofservice = new Uri("http://achrafbenalaya.com/");
                var license = new OpenApiLicense()
                {
                    Name = "MIT"
                };

                var contact = new OpenApiContact()
                {
                    Name = "achraf",
                    Email = "achrafbenalaya@gmail.com",
                    Url = new Uri("http://achrafbenalaya.com/")

                };


                config.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = titlebase + " V 1",
                    Description = desc,
                    Contact = contact,
                    License = license,
                    TermsOfService = termsofservice


                });

                config.SwaggerDoc("v2", new OpenApiInfo
                {
                    Version = "v2",
                    Title = titlebase + " V2",
                    Description = desc,
                    Contact = contact,
                    License = license,
                    TermsOfService = termsofservice


                });

            }

      );





        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            app.UseSwagger();
            app.UseSwaggerUI(c => {

                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V2");

            });



            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

 

Now we need to add a convention to let swagger understand the different API version’s :

public class GroupingByNamespaceConvention : IControllerModelConvention
 {
     public void Apply(ControllerModel controller)
     {
         var controllerNamespace = controller.ControllerType.Namespace;
         var apiVersion = controllerNamespace.Split(".").Last().ToLower();
         if (!apiVersion.StartsWith("v")) { apiVersion = "v1"; }
         controller.ApiExplorer.GroupName = apiVersion;
     }
 }

 

Now we must apply the convention. For that we need to go to Startup.cs  ,look for ConfigureServices() and add the convention:

services.AddControllers(options =>
{
options.Conventions.Add(new GroupingByNamespaceConvention());
});

 

Project Link

Full Demos:

Swagger
ShareTweet
Previous Post

Kubernetes is deprecating Docker runtime support !

Next Post

FIX – YouTube Thumbnail Not Showing on Facebook

Related Posts

Switch to Azure Container Registry from Docker Hub
Azure

From Docker Hub, switch to Azure Container Registry & AKS

January 16, 2023
132
How to setup nginx reverse proxy && load balancer for aspnet core apps with Docker and azure kubernetes service (AKS)
Azure

How to configure an ingress controller using TLS/SSL for the Azure Kubernetes Service (AKS)

November 25, 2022
229
How to setup nginx reverse proxy && load balancer for aspnet core apps with Docker and azure kubernetes service (AKS)
Azure

How to setup nginx reverse proxy && load balancer for aspnet core apps with Docker and azure kubernetes service (AKS)

November 23, 2022
102
How to setup nginx reverse proxy for aspnet core apps with and without  Docker compose
Azure

How to setup nginx reverse proxy for aspnet core apps with and without Docker compose

November 23, 2022
153
Win free certifications at the Microsoft Build Cloud Skills Challenge | May 2022 🎁
Blog

Win free certifications at the Microsoft Build Cloud Skills Challenge | May 2022 🎁

May 28, 2022
107
Generating report for SSL Certificates for Websites with PowerShell
Azure

Generating report for SSL Certificates for Websites with PowerShell

April 10, 2022
386
Next Post
Configure Azure Web App Logging With .NET 5

Configure Azure Web App Logging With .NET 5

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Terraform

Certifications

Microsoft certified trainer (MCT)

Recommended

How to SSH into AKS Nodes

How to SSH into AKS Nodes

May 11, 2021
3.8k
Dapr – Service Invocation Part 1/2

Dapr – Service Invocation Part 1/2

August 17, 2021
510
How to setup nginx reverse proxy && load balancer for aspnet core apps with Docker and azure kubernetes service (AKS)

How to configure an ingress controller using TLS/SSL for the Azure Kubernetes Service (AKS)

November 25, 2022
229
Sql tips and tricks

Sql tips

August 29, 2020
270
My book collection for 2020-2021

My book collection for 2020-2021

December 28, 2020
336
Where is my Money ! The Proper way To Shutdown Azure VM

Where is my Money ! The Proper way To Shutdown Azure VM

November 2, 2020
516
Facebook Twitter LinkedIn Youtube
Switch to Azure Container Registry from Docker Hub

From Docker Hub, switch to Azure Container Registry & AKS

January 16, 2023
How to setup nginx reverse proxy && load balancer for aspnet core apps with Docker and azure kubernetes service (AKS)

How to configure an ingress controller using TLS/SSL for the Azure Kubernetes Service (AKS)

November 25, 2022
How to setup nginx reverse proxy && load balancer for aspnet core apps with Docker and azure kubernetes service (AKS)

How to setup nginx reverse proxy && load balancer for aspnet core apps with Docker and azure kubernetes service (AKS)

November 23, 2022

Categories

  • Apps (1)
  • Azure (39)
  • blazor (2)
  • Blog (62)
  • c# (7)
  • Cloud (37)
  • Dapr (4)
  • docker (3)
  • Games (1)
  • General Tips & Fix (1)
  • motivation (2)
  • Motivation (3)
  • News (9)
  • Resume (1)
  • sql (4)
  • Tricks, Tips and Fixes (3)
  • xamarin (5)
No Result
View All Result
  • News
  • Blog
    • blazor
    • c#
    • Cloud
      • Azure
    • docker
    • sql
    • xamarin
    • Dapr
    • Tricks, Tips and Fixes
  • Cloud
  • Motivation
  • General Tips & Fix
  • Exam Preparation
    • AZ-104
    • AZ-400
  • About
    • Resume