Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular
    • C
    • c#
    • C#
    • HTML/CSS
    • Java
    • JavaScript
    • Node.js
    • Python
    • React
    • Security
    • SQL Server
    • TypeScript
  • Post Blog
  • Tools
    • JSON Beautifier
    • HTML Beautifier
    • XML Beautifier
    • CSS Beautifier
    • JS Beautifier
    • PDF Editor
    • Word Counter
    • Base64 Encode/Decode
    • Diff Checker
    • JSON to CSV
    • Password Generator
    • SEO Analyzer
    • Background Remover
  1. Home
  2. Blog
  3. How to use Swagger in Existing Asp.Net Core MVC Project

How to use Swagger in Existing Asp.Net Core MVC Project

Date- Jun 07,2022

11693

Swagger UI Swashbuckle

Swagger UI

Swagger is one of the popular tools which is widely used now a days for generating an interactive documentation UI. It generates an interactive API for the users so that they can understand about the API and use those more easily. The OpenAPI is a specification whereas the Swagger is a tool used for implementing the specification.

Integrating Swagger UI in existing Asp.Net Core Project

For integrating swagger in existing Asp.net Core project we have to install these swashbuckle packages

 Install-Package Swashbuckle -Version 5.6.0
 
 Install-Package Swashbuckle.AspNetCore -Version 6.3.1
 
 Install-Package Swashbuckle.AspNetCore.Swagger -Version 6.3.1

You can also install these packages in your Asp.Net Core project using nuget packages. You can have a look at the image.

After you have installed all these packages , now you have to go to startup.cs file and add the follow lines for swagger UI in Configure method. First of all add following namespace on startup.cs

using Swashbuckle.Swagger;

Now add following lines for swagger UI in the configure method

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();
            
            
            //Add These lines for swagger

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Test1 Api v1");
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();

               
            });
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("areaRoute", "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");


            });
        }

So, after adding the swagger code in the configure method we have to add following lines in the ConfigureServices method

 services.AddSwaggerGen(c =>
            {
                //c.SwaggerDoc("v1", new Info { Title = "You api title", Version = "v1" });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n 
                      Enter 'Bearer' [space] and then your token in the text input below.
                      \r\n\r\nExample: 'Bearer 12345abcdef'",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                  {
                    {
                      new OpenApiSecurityScheme
                      {
                        Reference = new OpenApiReference
                          {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        },
                          Scheme = "oauth2",
                          Name = "Bearer",
                          In = ParameterLocation.Header,

                      },
                        new List<string>()
                    }
                  });


            });

Please match your configureservices method to this code

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddRazorPages();
            services.AddSwaggerGen(c =>
            {
                //c.SwaggerDoc("v1", new Info { Title = "You api title", Version = "v1" });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = @"JWT Authorization header using the Bearer scheme. \r\n\r\n 
                      Enter 'Bearer' [space] and then your token in the text input below.
                      \r\n\r\nExample: 'Bearer 12345abcdef'",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement()
                  {
                    {
                      new OpenApiSecurityScheme
                      {
                        Reference = new OpenApiReference
                          {
                            Type = ReferenceType.SecurityScheme,
                            Id = "Bearer"
                        },
                          Scheme = "oauth2",
                          Name = "Bearer",
                          In = ParameterLocation.Header,

                      },
                        new List<string>()
                    }
                  });


            });
        }

So, Now we had done setting up swagger. Now we will add one api controller with name TestController. Now add one api for test purpose like we did in this image. 

Now , run your application and navigate to 

/swagger/Index.html

You will see your swagger documentation here

Here you will see your all api's listed. As soon as you will add any new api's and run the application. You will notice new api's will automatically show up here in the list. You can click on try out and execute the api with and without parameter . So this is how you can add swagger in you existing Asp.Net core application. You can download the attachment and check the source code to check swagger.

S
Shubham Saini
Programming author at Code2Night โ€” sharing tutorials on ASP.NET, C#, and more.
View all posts โ†’

Related Articles

Authentication for swagger UI in production in ASP.Net Core 6.0
Mar 04, 2024
Previous in ASP.NET Core
HttpCookies Issue with Asp.Net Core 3.1
Next in ASP.NET Core
How to export view as pdf in Asp.Net Core

Comments

Contents

๐ŸŽฏ

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 25933 views
  • Exception Handling Asp.Net Core 20717 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20195 views
  • How to implement Paypal in Asp.Net Core 19606 views
  • Task Scheduler in Asp.Net core 17494 views
View all ASP.NET Core posts โ†’

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Free Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Diff Checker
  • Base64 Encode/Decode
  • Word Counter
  • SEO Analyzer
By Language
  • Angular
  • C
  • c#
  • C#
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ยท  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor