Skip to content

Latest commit

 

History

History
81 lines (63 loc) · 1.82 KB

README.md

File metadata and controls

81 lines (63 loc) · 1.82 KB

Caravel.AspNetCore

This package contains reusable middleware, http utilities that every application needs.

  • Exception Middleware
// Handle exceptions according to RFC: https://tools.ietf.org/html/rfc7807
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();

// Map the middleware
_application.UseExceptionHandler();
{
  "code": "book_not_found",
  "title": "Book does not exist",
  "status": 404,
  "detail": "Book 53655b3d-48d5-4ac1-ba73-4318b3b702e8 does not exist",
}
  • ApiKey Endpoint Filter
services.Configure<ApiKeyOptions>(configuration.GetSection("Authentication"));

// Add to a group or single endpoints using: .AddEndpointFilter<ApiKeyEndpointFilter>();
var versionedGroup = application
    .MapGroup("api/v{version:apiVersion}")
    .WithApiVersionSet(apiVersionSet)
    .AddEndpointFilter<ApiKeyEndpointFilter>();
{
  "title": "Provide X-API-KEY header.",
  "status": 401,
  "code": "api_key_missing"
}
  • Endpoint Features

Add all endpoints features that implement IEndpointFeature interface.

builder.Services.AddEndpointFeatures(Assembly.GetExecutingAssembly());

Map feature endpoints.

ApiVersionSet apiVersionSet = app.NewApiVersionSet()
.HasApiVersion(new ApiVersion(1))
.ReportApiVersions()
.Build();

RouteGroupBuilder versionedGroup = app
.MapGroup("api/v{version:apiVersion}")
.WithApiVersionSet(apiVersionSet);

app.MapEndpointFeatures(versionedGroup);
  • User Context Implementation using HttpContextAccessor
// Requirement since it's injected in the UserContext implementation
services.AddHttpContextAccessor();
services.AddScoped<IUserContext, UserContext>();
// Inject IUserContext in your services

public MyService(IUserContext userContext) 
{
    var userId = userContext.UserId();
}