aspnet-api-versioning icon indicating copy to clipboard operation
aspnet-api-versioning copied to clipboard

Example Using Old Program/Startup Implementation

Open pfeurean opened this issue 4 years ago • 1 comments

Is there an example project that works with multiple api versions? I have a project that upgraded, it will only display the default version in swagger. There is a discussion (#820) that sounds like it should be working now. I can not get it to work at all. i've attached the Program.cs file from OpenApiExample of the repository. Any help would be appreciated.

using ApiVersioning.Examples;
using Asp.Versioning;
using Asp.Versioning.ApiExplorer;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;

namespace Asp.Versioning.WebApi.OpenApiExample;

public static class Program
{
    public static void Main( string[] args )
    {
        CreateHostBuilder( args ).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder( string[] args ) =>
        Host.CreateDefaultBuilder( args )
        .ConfigureWebHostDefaults( webBuilder => webBuilder.UseStartup<Startup>() );
}

public class Startup
{
    public void ConfigureServices( IServiceCollection services )
    {
        services.AddControllers();
        services.AddApiVersioning( options =>
                {
                    // reporting api versions will return the headers
                    // "api-supported-versions" and "api-deprecated-versions"
                    options.ReportApiVersions = true;
                } )
                .AddMvc()
                .AddApiExplorer( options =>
                {
                    // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
                    // note: the specified format code will format the version as "'v'major[.minor][-status]"
                    options.GroupNameFormat = "'v'VVV";

                    // note: this option is only necessary when versioning by url segment. the SubstitutionFormat
                    // can also be used to control the format of the API version in route templates
                    options.SubstituteApiVersionInUrl = true;
                } );

        services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerGenOptions>();
        services.AddTransient<IConfigureOptions<SwaggerUIOptions>, ConfigureSwaggerUIOptions>();

        services.AddSwaggerGen( options =>
                {
                    options.ResolveConflictingActions( conflicts => {
                        return conflicts.First();
                    } );
                    options.CustomSchemaIds( x =>
                    {
                        var schemaId = x.FullName;

                        if ( x.FullName.StartsWith( "ApiVersioning.Examples" ) )
                        {
                            var splits = x.FullName.Split( "." );
                            var sh = splits[0];
                            var api = splits[2];
                            schemaId = string.Join( ".", new[] { sh, string.Equals( api, "aspnetcore", System.StringComparison.OrdinalIgnoreCase ) ? null : api, x.Name }.Where( x => x != null ) );
                        }

                        return schemaId;
                    } );

                    // add a custom operation filter which sets default values
                    options.OperationFilter<SwaggerDefaultValues>();

                    var fileName = typeof( Program ).Assembly.GetName().Name + ".xml";
                    var filePath = Path.Combine( AppContext.BaseDirectory, fileName );

                    // integrate xml comments
                    options.IncludeXmlComments( filePath );
                } );
    }

    public void Configure( IApplicationBuilder app, IApiVersionDescriptionProvider provider )
    {
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthorization();

        app.UseEndpoints( endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapSwagger( setupAction: options => options.PreSerializeFilters.Add( ( swagger, httpReq ) => swagger.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}" } } ) );
        } );

        app.UseSwagger();
        app.UseSwaggerUI();
    }
}

public class ConfigureSwaggerUIOptions : IConfigureOptions<SwaggerUIOptions>
{
    private readonly IApiVersionDescriptionProvider provider;

    public ConfigureSwaggerUIOptions( IApiVersionDescriptionProvider provider ) => this.provider = provider;

    public void Configure( SwaggerUIOptions options )
    {
        var descriptions = provider.ApiVersionDescriptions;
        foreach ( var description in descriptions )
        {
            var url = $"/swagger/{description.GroupName}/swagger.json";
            var name = description.GroupName.ToUpperInvariant();
            options.SwaggerEndpoint( url, name );
        }
    }
}
 

pfeurean avatar Jun 04 '22 21:06 pfeurean

It would seem you figured out the solution on your own. The setup provided looks correct. If you're using Preview 3, then it should have worked.

commonsensesoftware avatar Jun 06 '22 15:06 commonsensesoftware