SHARE:

ASP.NET Core7: Use endpoint groups to manage minimal APIs versioning

Introduction

This year .NET 7 ships with ASP.NET Core 7 and the latter brings big improvements on Minimal APIs. Let me introduce you the endpoint groups feature, which applies on Minimal APIs only. Endpoint groups are a way to declare some common routing information across several minimal endpoints, but more also, like constraints such as Authorization, CORS rules etc etc…. We will see in this post what you can do with endpoint groups and how useful it could be.

What are endpoint groups

Endpoint groups allow you to apply constraints and rules on a bunch of minimal endpoints. ASP.NET Core 7 provides a RouteGroupBuilder class to build your rules and group your endpoints. Let’s create two groups of endpoint, each one contains two GET endpoints, materialized with the MapGet method:

I strongly suggest you, for readability purpose to group only endpoints in separate extension methods, like above, and not to apply any constraint there. If you wanna add constraints/rules and base route you can do it directly in the Program.cs file, so, by reading your endpoint groups, you’ll see fastly what group has what constraint/rule or base route. The following code shows how to add constraints, rules and base route:

As you can see, group one has a CORS policy applied on it while group two has another CORS policy, Authorization and RateLimiting rules.

Use endpoint groups to manage minimal API versioning

Endpoint groups allow you to manage API versioning. Simply add a base route on the MapGroup method, example: MapGroup(“/v1”) or MapGroup(“/v2”). To make it work with Swagger add the following Nuget package:

NuGet\Install-Package Microsoft.AspNetCore.OpenApi -Version 7.0.4

Then add the following extensions on the IServiceCollection builder:

  • AddEndpointsApiExplorer();
  • AddSwaggerGen();

Note that the AddEndpointsApiExplorer() extension method is made to make Minimal APIs visible to Swagger.

Once done add the following Swagger middlewares on the ASP.NET Core pipeline:

  • UseSwagger();
  • UseSwaggerUI();

To make your Swagger documentation clearer (clear distinction between endpoint groups in SwaggerUI) you can use the WithTags extensions methods and name them as follow:

Demo

If you lunch the following URL (which is defined like this by default) : /swagger/index.html you should see something like this:

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.