Github:https://github.com/scalar/scalar
Nuget:Scalar.AspNetCore
环境:Net9
启用Scalar
if (app.Environment.IsDevelopment())
{app.MapScalarApiReference(opt =>{opt.DarkMode = false;}); // http://ip:port/scalar/v1app.MapOpenApi();
}
Program.cs
public class Program
{public static void Main(string[] args){var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddControllers();// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapibuilder.Services.AddOpenApi();builder.Services.AddOpenApi(opt =>{opt.AddDocumentTransformer<BearerSecuritySchemeTransformer>();});var app = builder.Build();// Configure the HTTP request pipeline.if (app.Environment.IsDevelopment()){app.MapScalarApiReference(opt =>{opt.DarkMode = false;}); // http://ip:port/scalar/v1app.MapOpenApi();}app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();}public sealed class BearerSecuritySchemeTransformer(IAuthenticationSchemeProvider authenticationSchemeProvider) : IOpenApiDocumentTransformer{public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken){var authenticationSchemes = await authenticationSchemeProvider.GetAllSchemesAsync();if (authenticationSchemes.Any(authScheme => authScheme.Name == "Bearer")){// Add the security scheme at the document levelvar requirements = new Dictionary<string,OpenApiSecurityScheme>{["Bearer"] = new OpenApiSecurityScheme{Type = SecuritySchemeType.Http,Scheme = "bearer", // "bearer" refers to the header name hereIn = ParameterLocation.Header,BearerFormat = "Json Web Token"}};document.Components ??= new OpenApiComponents();document.Components.SecuritySchemes = requirements;// Apply it as a requirement for all operationsforeach (var operation in document.Paths.Values.SelectMany(path => path.Operations)){operation.Value.Security.Add(new OpenApiSecurityRequirement{[new OpenApiSecurityScheme{Reference = new OpenApiReference{Id = "Bearer",Type = ReferenceType.SecurityScheme}}] = Array.Empty<string>()});}}}}
}