Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement IApiVersionDescriptionProvider to Program.cs in .NET 6

I'm using .NET 6.

I'm doing make Versioning for my Web API Core. And I got stucked when implementing the IApiVersionDescriptionProvider into Program.cs.

Beacuse of when creating a new project ASP.NET Core Web API, there only the program.cs file. (The old .NET Core have Startup.cs and Program.cs)

Please help me, Thanks all Here is my code

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;
using VfcSolution.Application.User;
using VfcSolution.WebApi;
using VfcSolution.WebApi.VfcSolutionMapper;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddScoped<IUserRepository, OracleUserRepository>();

builder.Services.AddAutoMapper(typeof(VfcSolutionMappings));

builder.Services.AddApiVersioning(options =>
{
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.ReportApiVersions = true;
});

builder.Services.AddVersionedApiExplorer(options => options.GroupNameFormat = "'v'VVV");

builder.Services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
builder.Services.AddSwaggerGen();

builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

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

app.UseSwagger();

app.UseSwaggerUI(options =>
{   
    ==> I'M STUCKED IN HERE, I DO NOT KNOW HOW TO IMPLEMENT IApiVersionDescriptionProvider
    foreach (var desc in provider.ApiVersionDescriptions)
    {

    }
});

app.UseAuthorization();

app.MapControllers();

app.Run();
like image 991
Nguyen Nhan Avatar asked Dec 28 '25 12:12

Nguyen Nhan


1 Answers

You need to add the following line after builder.Build();

 using Microsoft.AspNetCore.Mvc.ApiExplorer;

 var app = builder.Build();
 var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
like image 119
Mirzodaler Avatar answered Jan 03 '26 09:01

Mirzodaler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!