Using Swagger in an Asp.Net App

December 04, 2022

One of the interesting challenges with Asp.Net MVC when you first start out, is getting the routing right. In this article, we’ll cover a technique to debug the routing of endpoints in your project.

Swagger

Swagger is a tool that basically discovers and displays the endpoints of your API. You may be familiar with using this with a Web API, but you can just as easily add it to an Asp.Net app.

If you’d prefer, you can simply follow the Microsoft documentation.

Install the package

You’ll need to start by installing the Swagger NuGet Package:

Install-Package Swashbuckle.AspNetCore

Code

Once that’s installed, Add the following code to your Program.cs (or Startup.cs if you’re prior to .Net 6):

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

// Add Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

You’ll also need to call the Use methods further down. This is restricted to debugging only (clearly providing a map of internal endpoints within your application has a potential security issue):

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

Now, when you run your app, you can simply navigate to:

https://localhost:1234/swagger/index.html

And you should see a map of the endpoints - you’ll even be able to call them via the UI.

It’s worth noting that you’ll only see endpoints that have an explicit path specified; for example, you won’t see:

[HttpPost]
public async Task<IActionResult> Lookup(MyViewModel myViewModel)

But you will see:

[HttpPost("lookup")]
public async Task<IActionResult> Lookup(MyViewModel myViewModel)


Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024