Modern web development often demands a hybrid approach. While traditional ASP.NET Core MVC projects are famous for rendering server-side HTML views using Razor, many applications also need to expose robust RESTful APIs to power mobile apps, single-page applications (SPAs), or third-party integrations.
When you build APIs, documenting them clearly is just as important as writing the code. This is where Swagger (OpenAPI) comes in. Swagger automatically generates interactive documentation, allowing developers, testers, and clients to explore and test your endpoints directly from a web browser without needing external tools like Postman.
In this comprehensive guide, we will walk through setting up Swagger in an ASP.NET Core MVC project step by step.
Why Use Swagger in an MVC Project?
ASP.NET Core MVC naturally handles both MVC controllers (which return views) and API controllers (which return JSON/data). Integrating Swagger into this setup offers several key benefits:
Interactive Documentation: Generates a clean UI where users can see endpoints, HTTP methods, request parameters, and response models.
Live Testing: Allows you to execute requests directly via the "Try it out" feature.
Standards Compliance: Built on the OpenAPI Specification, making it universally recognized across different development tools and ecosystems.
Step 1: Install the Swashbuckle NuGet Package
ASP.NET Core does not include Swagger generation out of the box, but the open-source Swashbuckle.AspNetCore package makes integration seamless. It consists of a Swagger generator, a Swagger document middleware, and a built-in Swagger UI.
Open your terminal, navigate to your project directory, and run the following command:
Bash
dotnet add package Swashbuckle.AspNetCore
(Alternatively, you can install it via the NuGet Package Manager UI in Visual Studio by searching for Swashbuckle.AspNetCore).
Step 2: Register Swagger Services in Program.cs
Next, you need to configure the Dependency Injection container in your Program.cs file. Because an MVC project handles both views and API controllers, you want to ensure controller support is enabled alongside the API metadata explorers.
Update your Program.cs file with the following configuration:
C#
var builder = WebApplication.CreateBuilder(args);
// 1. Add services to the container (supports both MVC views and API controllers)
builder.Services.AddControllersWithViews();
// Required to gather metadata for API endpoints
builder.Services.AddEndpointsApiExplorer();
// Register the Swagger generator, defining a Swagger document
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
{
Title = "My Hybrid ASP.NET Core MVC API",
Version = "v1",
Description = "An API documentation guide for my MVC and Web API project."
});
});
var app = builder.Build();
Step 3: Configure the Middleware Pipeline
Once the services are registered, you must configure the HTTP request pipeline to serve the Swagger JSON file and the interactive UI. It is standard practice to enable Swagger only during development to protect production infrastructure.
Add the following middleware configuration right after building the app:
C#
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
// Optional: Set RoutePrefix to string.Empty if you want Swagger UI
// to load directly at the root URL (e.g., https://localhost:xxxx/)
// options.RoutePrefix = string.Empty;
});
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
// Map traditional MVC controller routes (for Razor views)
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
// Map attribute-routed API controllers
app.MapControllers();
app.Run();
Step 4: Create a Sample API Controller
To see Swagger in action, you need an API controller. In ASP.NET Core, API controllers are typically decorated with the [ApiController] attribute and inherit from ControllerBase (unlike MVC controllers which inherit from Controller and return views).
Create a new file named ProductsController.cs inside your Controllers folder:
C#
using Microsoft.AspNetCore.Mvc;
namespace YourProjectName.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
// GET: api/products
[HttpGet]
public IActionResult GetAllProducts()
{
var products = new[]
{
new { Id = 1, Name = "Mechanical Keyboard", Price = 89.99 },
new { Id = 2, Name = "Wireless Mouse", Price = 45.50 },
new { Id = 3, Name = "UltraWide Monitor", Price = 399.00 }
};
return Ok(products);
}
// GET: api/products/5
[HttpGet("{id}")]
public IActionResult GetProductById(int id)
{
return Ok(new { Id = id, Name = $"Product Sample {id}", Price = 99.99 });
}
}
}
Step 5: Run and Test Your API
Build and run your application using
dotnet runor by pressingF5in Visual Studio.Open your web browser and navigate to your application's base URL followed by
/swagger(for example,https://localhost:5001/swagger).You will be greeted by the Swagger UI interface, listing your
Productscontroller along with itsGETendpoints.Click on an endpoint, hit Try it out, and click Execute to see live JSON responses returned directly from your application.
Pro-Tips for Production-Ready Swagger
As your project grows, you can take your Swagger implementation further with these best practices:
XML Comments: Enable XML documentation documentation in your
.csprojfile and configure Swagger to read it so that code summaries and method descriptions appear in the UI.JWT Authentication: Add security definitions to
AddSwaggerGenso developers can input bearer tokens and test secure endpoints directly inside Swagger UI.Multiple Versions: Use Swagger to manage multiple API versions (
v1,v2) seamlessly as your application evolves.

Join the conversation! Your thoughts help the community grow.