Thursday, December 12, 2024

ASP.NET Core 9.0: Microsoft.AspNetCore.OpenApi and Swagger UI

With the release of .NET 9.0, you might have noticed for ASP.NET Core Web Application templates in Visual Studio, we no longer have Swagger UI configured.

It basically looks like below.

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();

WebApplication app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.UseHttpsRedirection();

...

By default route to the OpenAPI specification will be https://<applicationUrl>/openapi/v1.json.

So far ASP.NET Core team hasn't announced (or I have not seen) their own UI for viewing OpenAPI specification. 

We can still use Swagger UI to view the OpenAPI specification.

First we need to install the package: Swashbuckle.AspNetCore.SwaggerUI.

Then we can do either one of this.

  • Update the Open API document route to the route Swagger UI expects
// Option 1: Update the Open API document route to the route Swagger UI expects
app.MapOpenApi("swagger/v1/swagger.json");
app.UseSwaggerUI();
Update the Open API document route to the route Swagger UI expects
  • Update Swagger UI to use the Open API document route
// Option 2: Update Swagger UI to use the Open API document route
app.MapOpenApi();
app.UseSwaggerUI(x =>
{
    x.SwaggerEndpoint("/openapi/v1.json""My API");
});
Update Swagger UI to use the Open API document route

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment