Thomas
August
Ryan

Work Posts Résumé

Expose Swagger docs at both the default and root Route of your .NET 6 Web API

By default, the interactive docs in your .NET 6 Web API will be routed to the “/swagger” endpoint if you follow this tutorial.

This is cool because it is consistent across projects, but it’s not ideal because your app will return a 404 if you browse to the root or “/” endpoint. To solve this problem Microsoft suggests in their docs that you can set the RoutePrefix in your UseSwaggerUI to string.Empty. This will work and when you browse to the root route of your app, you’ll now see the docs.

But you’ll also no longer see the docs at the “/swagger” route which can be problematic if Visual Studio 2022 or the API’s consumer expect it to be there by convention.

To solve this problem and have it both ways you can duplicate the “UseSwaggerUI” call in your apps Startup.cs file. One version that includes the option to set the RoutePrefix to string.Empty and another that skips that line. Now when you start up your Web API you’ll be greeted with the docs whether you start at the conventional “/swagger” route or at the app’s root route.

For an example of how this looks check out this code on Github.