I'm creating a new ASP.NET Core 8 Web API. In my previous projects with .NET 6 or .NET 7, I can use:
services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
});
services.AddVersionedApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
Now, the package Microsoft.AspNetCore.Mvc.ApiExplorer
is deprecated and I replaced it with the new one Asp.Versioning.Mvc.ApiExplorer
but there is no extension for AddVersionedApiExplorer
.
In the configuration for Swagger, I have the following code:
public class ConfigureSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
{
private readonly IApiVersionDescriptionProvider _provider;
public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider)
{
_provider = provider;
}
public void Configure(SwaggerGenOptions options)
{
foreach (var description in _provider.ApiVersionDescriptions)
{
options.SwaggerDoc(
description.GroupName,
CreateVersionInfo(description));
}
}
public void Configure(string name, SwaggerGenOptions options)
{
Configure(options);
}
private static OpenApiInfo CreateVersionInfo(
ApiVersionDescription description)
{
var info = new OpenApiInfo()
{
Title = "Test API",
Version = description.ApiVersion.ToString(),
Description = "This is a test API.",
};
if (description.IsDeprecated)
{
info.Description += " This API version has been deprecated.";
}
return info;
}
}
When I run the application, I get this error
Unable to resolve service for type 'Asp.Versioning.ApiExplorer.IApiVersionDescriptionProvider' while attempting to activate 'Middletier.Api.Extensions.Configuration.ConfigureSwaggerOptions'.
How can I fix it?
AddApiVersioning
works a bit different (it returns IApiVersioningBuilder
). Install Asp.Versioning.Mvc.ApiExplorer
which will allow to call AddApiExplorer
on IApiVersioningBuilder
returned by AddApiVersioning
:
builder.Services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
})
.AddApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
See the Quick Start, samples and this question - ApiVersion attribute not working in .NET 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With