Class ApiExtensions
Namespace: Momentum.ServiceDefaults.Api
Assembly: Momentum.ServiceDefaults.Api.dll
Provides extension methods for configuring API services with sensible defaults.
[ExcludeFromCodeCoverage]
public static class ApiExtensionsInheritance
Inherited Members
object.GetType(), object.MemberwiseClone(), object.ToString(), object.Equals(object?), object.Equals(object?, object?), object.ReferenceEquals(object?, object?), object.GetHashCode()
Methods
AddApiServiceDefaults(WebApplicationBuilder, bool)
Adds default API services to the application builder (excluding OpenAPI).
public static IHostApplicationBuilder AddApiServiceDefaults(this WebApplicationBuilder builder, bool requireAuth = true)Parameters
builder WebApplicationBuilder
The web application builder to configure.
requireAuth bool
When true (default), registers authentication and authorization services with a fallback policy that requires all endpoints (minimal API and gRPC) to be authenticated. Individual endpoints can opt out with [AllowAnonymous] or .AllowAnonymous(). Development-only endpoints (OpenAPI, Scalar, gRPC reflection) are automatically marked as anonymous. When false, no authentication or authorization services are registered.
Returns
The configured host application builder for method chaining.
Remarks
Important: This method does not configure OpenAPI. For XML documentation support with OpenAPI, call AddOpenApi() directly in your API project's Program.cs. This allows the .NET 10 source generator to intercept the call and generate XML comment transformers.
Service Configuration
This method configures the following services:
- MVC Controllers: With endpoint API explorer
- Problem Details: For standardized error responses
- OpenAPI: With XML documentation support
- HTTP Request/Response Logging: For debugging and monitoring
- gRPC Services: With reflection support
- Authentication and Authorization: Services setup
- Kestrel Server Configuration: Removes server header for security
Service Registration Details
MVC Controllers with Custom Routing
builder.Services.AddControllers(opt =>
{
opt.Conventions.Add(new RouteTokenTransformerConvention(new KebabCaseRoutesTransformer()));
});API Documentation Services
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddProblemDetails();
builder.Services.AddAutoProducesConvention(); // Auto-infer response types for OpenAPI
builder.Services.AddHttpLogging();gRPC Services
builder.Services.AddGrpc();
builder.Services.AddGrpcReflection();Security Services
builder.Services.AddAuthentication();
builder.Services.AddAuthorization();Server Configuration
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.AddServerHeader = false;
});Application Configuration
This method configures the following middleware and endpoints:
- HTTP Logging Middleware: For request/response logging
- Routing, Authentication, and Authorization: Core ASP.NET Core middleware
- gRPC-Web Support: With default enablement for browser clients
- HSTS and Exception Handling: In production environments
- OpenAPI, Scalar Documentation, and gRPC Reflection: In development
- Controller Endpoints: With optional authorization requirement
- gRPC Service Endpoints: For gRPC communication
Middleware Pipeline Configuration
Core Middleware
app.UseHttpLogging();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();gRPC-Web Support
app.UseGrpcWeb(new GrpcWebOptions { DefaultEnabled = true });Production Middleware
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
app.UseExceptionHandler();
}Development Tools
if (app.Environment.IsDevelopment())
{
app.MapOpenApi().CacheOutput();
app.MapScalarApiReference(options => options.WithTitle($"{app.Environment.ApplicationName} OpenAPI"));
app.MapGrpcReflectionService();
}Endpoint Configuration
var controllersEndpointBuilder = app.MapControllers();
if (requireAuth)
controllersEndpointBuilder.RequireAuthorization();
app.MapGrpcServices();Route Transformation
Kebab Case Routing
The extensions configure kebab-case routing transformation:
opt.Conventions.Add(new RouteTokenTransformerConvention(new KebabCaseRoutesTransformer()));This transforms controller and action names:
UserController.GetUser→/user/get-userOrderController.CreateOrder→/order/create-order
OpenAPI Integration
XML Documentation Support
// Call AddOpenApi() directly in your API project for XML documentation support
// AddAutoProducesConvention() is already included in AddApiServiceDefaults()
builder.Services.AddOpenApi(options => options.ConfigureOpenApiDefaults());The .NET 10 source generator automatically enriches OpenAPI with XML comments when:
GenerateDocumentationFileis set totruein your projectAddOpenApi()is called directly in your API project (not from a library)- The
InterceptorsNamespacesincludesMicrosoft.AspNetCore.OpenApi.Generated
Scalar Documentation
app.MapScalarApiReference(options => options.WithTitle($"{app.Environment.ApplicationName} OpenAPI"));Provides modern API documentation interface with:
- Interactive Testing: Built-in API explorer
- Code Generation: Client SDK examples
- Schema Visualization: Type definitions and relationships
gRPC Configuration
Service Registration
builder.Services.AddGrpc();
builder.Services.AddGrpcReflection();Web Support
app.UseGrpcWeb(new GrpcWebOptions { DefaultEnabled = true });Enables:
- Browser Compatibility: gRPC calls from web browsers
- Streaming Support: Bidirectional streaming over HTTP/1.1
- Protocol Translation: gRPC-Web to gRPC protocol bridging
Development Reflection
app.MapGrpcReflectionService();Provides:
- Service Discovery: Runtime service enumeration
- Tool Integration: Support for gRPC clients and testing tools
- Development Experience: Service exploration and debugging
Security Considerations
Server Header Removal
serverOptions.AddServerHeader = false;Removes the Server header to:
- Reduce Information Disclosure: Hide implementation details
- Security Best Practice: Minimize attack surface
- Compliance: Meet security scanning requirements
HSTS Configuration
app.UseHsts();Enforces HTTPS in production:
- Browser Security: Prevents protocol downgrade attacks
- Certificate Pinning: Validates server certificates
- Compliance: Meets modern security standards
Environment-Specific Configuration
Development Features
Only enabled in development:
- OpenAPI Documentation: Interactive API docs
- gRPC Reflection: Service discovery
- Caching Middleware: Performance optimization for docs
Production Optimizations
Only enabled in production:
- HSTS: HTTP Strict Transport Security
- Exception Handling: Structured error responses
Authorization Flexibility
Optional Authorization
public static WebApplication ConfigureApiUsingDefaults(this WebApplication app, bool requireAuth = true)The requireAuth parameter allows:
- Public APIs: Set to
falsefor open endpoints - Secure APIs: Default
truefor protected resources - Mixed Scenarios: Selective authorization per endpoint
ConfigureApiUsingDefaults(WebApplication)
Configures the web application with default API middleware and endpoints.
public static WebApplication ConfigureApiUsingDefaults(this WebApplication app)Parameters
app WebApplication
The web application to configure.
Returns
The configured web application for method chaining.
Remarks
API Extensions
Service Configuration
This method configures the following services:
- MVC Controllers: With endpoint API explorer
- Problem Details: For standardized error responses
- OpenAPI: With XML documentation support
- HTTP Request/Response Logging: For debugging and monitoring
- gRPC Services: With reflection support
- Authentication and Authorization: Services setup
- Kestrel Server Configuration: Removes server header for security
Service Registration Details
MVC Controllers with Custom Routing
builder.Services.AddControllers(opt =>
{
opt.Conventions.Add(new RouteTokenTransformerConvention(new KebabCaseRoutesTransformer()));
});API Documentation Services
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddProblemDetails();
builder.Services.AddAutoProducesConvention(); // Auto-infer response types for OpenAPI
builder.Services.AddHttpLogging();gRPC Services
builder.Services.AddGrpc();
builder.Services.AddGrpcReflection();Security Services
builder.Services.AddAuthentication();
builder.Services.AddAuthorization();Server Configuration
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.AddServerHeader = false;
});Application Configuration
This method configures the following middleware and endpoints:
- HTTP Logging Middleware: For request/response logging
- Routing, Authentication, and Authorization: Core ASP.NET Core middleware
- gRPC-Web Support: With default enablement for browser clients
- HSTS and Exception Handling: In production environments
- OpenAPI, Scalar Documentation, and gRPC Reflection: In development
- Controller Endpoints: With optional authorization requirement
- gRPC Service Endpoints: For gRPC communication
Middleware Pipeline Configuration
Core Middleware
app.UseHttpLogging();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();gRPC-Web Support
app.UseGrpcWeb(new GrpcWebOptions { DefaultEnabled = true });Production Middleware
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
app.UseExceptionHandler();
}Development Tools
if (app.Environment.IsDevelopment())
{
app.MapOpenApi().CacheOutput();
app.MapScalarApiReference(options => options.WithTitle($"{app.Environment.ApplicationName} OpenAPI"));
app.MapGrpcReflectionService();
}Endpoint Configuration
var controllersEndpointBuilder = app.MapControllers();
if (requireAuth)
controllersEndpointBuilder.RequireAuthorization();
app.MapGrpcServices();Route Transformation
Kebab Case Routing
The extensions configure kebab-case routing transformation:
opt.Conventions.Add(new RouteTokenTransformerConvention(new KebabCaseRoutesTransformer()));This transforms controller and action names:
UserController.GetUser→/user/get-userOrderController.CreateOrder→/order/create-order
OpenAPI Integration
XML Documentation Support
// Call AddOpenApi() directly in your API project for XML documentation support
// AddAutoProducesConvention() is already included in AddApiServiceDefaults()
builder.Services.AddOpenApi(options => options.ConfigureOpenApiDefaults());The .NET 10 source generator automatically enriches OpenAPI with XML comments when:
GenerateDocumentationFileis set totruein your projectAddOpenApi()is called directly in your API project (not from a library)- The
InterceptorsNamespacesincludesMicrosoft.AspNetCore.OpenApi.Generated
Scalar Documentation
app.MapScalarApiReference(options => options.WithTitle($"{app.Environment.ApplicationName} OpenAPI"));Provides modern API documentation interface with:
- Interactive Testing: Built-in API explorer
- Code Generation: Client SDK examples
- Schema Visualization: Type definitions and relationships
gRPC Configuration
Service Registration
builder.Services.AddGrpc();
builder.Services.AddGrpcReflection();Web Support
app.UseGrpcWeb(new GrpcWebOptions { DefaultEnabled = true });Enables:
- Browser Compatibility: gRPC calls from web browsers
- Streaming Support: Bidirectional streaming over HTTP/1.1
- Protocol Translation: gRPC-Web to gRPC protocol bridging
Development Reflection
app.MapGrpcReflectionService();Provides:
- Service Discovery: Runtime service enumeration
- Tool Integration: Support for gRPC clients and testing tools
- Development Experience: Service exploration and debugging
Security Considerations
Server Header Removal
serverOptions.AddServerHeader = false;Removes the Server header to:
- Reduce Information Disclosure: Hide implementation details
- Security Best Practice: Minimize attack surface
- Compliance: Meet security scanning requirements
HSTS Configuration
app.UseHsts();Enforces HTTPS in production:
- Browser Security: Prevents protocol downgrade attacks
- Certificate Pinning: Validates server certificates
- Compliance: Meets modern security standards
Environment-Specific Configuration
Development Features
Only enabled in development:
- OpenAPI Documentation: Interactive API docs
- gRPC Reflection: Service discovery
- Caching Middleware: Performance optimization for docs
Production Optimizations
Only enabled in production:
- HSTS: HTTP Strict Transport Security
- Exception Handling: Structured error responses
Authorization Flexibility
Optional Authorization
public static WebApplication ConfigureApiUsingDefaults(this WebApplication app, bool requireAuth = true)The requireAuth parameter allows:
- Public APIs: Set to
falsefor open endpoints - Secure APIs: Default
truefor protected resources - Mixed Scenarios: Selective authorization per endpoint