Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. 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 Updated Mar 2026 11757
Swagger UI Swashbuckle

What is Swagger?

Swagger is a set of open-source tools that helps developers design, build, document, and consume RESTful web services. It provides a user-friendly interface for testing APIs, making it easier for developers to understand how their APIs work. Swagger is based on the OpenAPI Specification, which is a standard for defining REST APIs. By using Swagger, developers can create interactive documentation that describes their API endpoints, request/response formats, and authentication methods.

In real-world applications, Swagger is invaluable for both development and collaboration. It allows developers to quickly test API endpoints, generate client SDKs, and share API documentation with stakeholders. This reduces the learning curve for new team members and ensures consistent API usage across different projects.

Prerequisites

  • Visual Studio 2019 or later installed
  • Basic knowledge of ASP.NET Core MVC
  • An existing ASP.NET Core MVC project
  • The NuGet package manager for installing required packages

Integrating Swagger UI in an Existing ASP.NET Core Project

To integrate Swagger into your existing ASP.NET Core project, you need to install the required NuGet packages. Open the Package Manager Console and run the following commands:

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 directly through the NuGet Package Manager in Visual Studio, as shown in the image below:

How to use Swagger in  Existing AspNet Core MVC Project

Once the packages are installed, you need to configure Swagger in your Startup.cs file. Start by adding the following namespace:

using Swashbuckle.AspNetCore.Swagger;

Next, you will need to update the Configure method to enable Swagger and Swagger UI:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
} else {
app.UseExceptionHandler("/Error");
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 Test API v1");
});
app.UseEndpoints(endpoints => {
endpoints.MapRazorPages();
endpoints.MapControllerRoute("areaRoute", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}

After adding the Swagger configuration code in the Configure method, you also need to update the ConfigureServices method:

public void ConfigureServices(IServiceCollection services) {
services.AddControllersWithViews();
services.AddRazorPages();
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your 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>() { }
}
});
});
}

Now that Swagger is set up, you can create a simple API controller. Create a new controller named TestController and add a sample API action:

[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase {
[HttpGet]
public IActionResult Get() {
return Ok(new { Message = "Hello, World!" });
}
}

After implementing the controller, run your application and navigate to /swagger/index.html. You will see your Swagger documentation and the interactive API interface:

How to use Swagger in  Existing AspNet Core MVC Project 2

Testing Your API with Swagger

Swagger UI allows you to test your API endpoints directly from the documentation interface. You can make requests to your API and see the responses in real-time. To test your API, follow these steps:

  1. Navigate to the Swagger UI in your browser.
  2. Locate the endpoint you want to test (e.g., /api/test).
  3. Click on the Try it out button.
  4. Click Execute to send the request.

The response will be displayed below the request area, showing the status code, response body, and any other relevant information. This feature is incredibly useful for debugging and understanding how your API behaves.

How to use Swagger in  Existing AspNet Core MVC Project 3

Edge Cases & Gotchas

While integrating Swagger into your ASP.NET Core project is straightforward, there are some common edge cases and gotchas to be aware of:

  • Versioning: If your API has multiple versions, ensure you create separate Swagger documents for each version. You can do this by calling c.SwaggerDoc multiple times with different names.
  • Security Schemes: If your API uses multiple authentication methods, ensure you define each method in the Swagger configuration. This will help users understand how to authenticate properly.
  • Custom Route Attributes: If you use custom routing attributes, make sure they are correctly reflected in your Swagger documentation. You may need to adjust your Swagger configuration to accommodate these routes.

Performance & Best Practices

To get the most out of Swagger in your ASP.NET Core project, consider the following best practices:

  • Keep Documentation Updated: Always keep your Swagger documentation in sync with your API changes. Outdated documentation can lead to confusion and errors.
  • Utilize XML Comments: By enabling XML comments in your project and configuring Swagger to include them, you can enhance your API documentation with detailed descriptions for each endpoint.
  • Limit Exposure of Sensitive Data: Be cautious about exposing sensitive information in your API responses. Use the ApiResponse attribute to control what data is displayed in Swagger.
  • Use API Versioning: Implement API versioning to manage breaking changes and ensure backward compatibility. Swagger can help document these versions effectively.

Conclusion

Integrating Swagger into your ASP.NET Core MVC project is a valuable step towards creating a well-documented and easily testable API. By following the steps outlined in this guide, you can enhance your development process and make it easier for users to interact with your API.

  • Swagger provides interactive API documentation for better understanding and testing.
  • Installation involves adding NuGet packages and configuring the Startup.cs file.
  • Testing APIs directly from Swagger UI streamlines debugging and development.
  • Be aware of edge cases and best practices to optimize your Swagger integration.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Mastering HTTP Client in Angular: A Comprehensive Guide to REST API Integration
Mar 26, 2026
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
Buy me a pizza

Comments

On this page

🎯

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 26052 views
  • Exception Handling Asp.Net Core 20792 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20276 views
  • How to implement Paypal in Asp.Net Core 19669 views
  • Task Scheduler in Asp.Net core 17570 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 | 1760
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
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • 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