Friday, July 16, 2021

.NET 6 Preview 6: Introducing OpenAPI Support in Minimal APIs in ASP.NET Core

We are getting closer to .NET 6 final release and this week .NET 6 Preview 6 was released. .NET 6 Preview 4 has introduced Minimal APIs in ASP.NET Core. With .NET 6 Preview 6, we now have OpenAPI support for Minimal APIs. In this post, let's see how we can set up Swagger for a project that uses the Minimal API approach.

If you are new to Minimal APIs in ASP.NET Core or need to refresh your memories, you can read this post I have written a couple of months back: .NET 6 Preview 4: Introducing Minimal APIs in ASP.NET Core. I am going to upgrade the sample project (minimal-api) used in that post to .NET 6 Preview 6 and add support for OpenAPI.

First, I am upgrading all the relevant packages to their latest previews, and I am installing Swashbuckle.AspNetCore latest package.
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <LangVersion>preview</LangVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0-preview.6.21352.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0-preview.6.21352.12" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.1.4" />
  </ItemGroup>

</Project>
In my case, I had only 2 packages installed.
Once the packages are updated, setting up Swagger is pretty straightforward, it's more or less the same to what we have done over all these years.

First, set up the required dependencies.
builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1"new OpenApiInfo { Title = "Minimal API", Description = "OpenAPI specification for Minimal API", Version = "v1" });
});
Then add Swagger OpenAPI specification and Swagger UI to the middleware.
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json""Minimal API V1");
});
That's just it. Now run the application and navigate to https://localhost:5001/swagger and we have Swagger specification at our disposal.
Swagger UI
You can find the sample code here,
   https://github.com/jaliyaudagedara/minimal-api 
      (Commit for Updating packages to .NET Preview 6 and adding OpenAPI support)

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment