| | | 1 | | using Elsa.Common.Multitenancy; |
| | | 2 | | using JetBrains.Annotations; |
| | | 3 | | using Microsoft.AspNetCore.Http; |
| | | 4 | | |
| | | 5 | | namespace Elsa.Tenants.AspNetCore.Middleware; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Middleware to initialize the tenant for each incoming HTTP request. |
| | | 9 | | /// </summary> |
| | | 10 | | [UsedImplicitly] |
| | 0 | 11 | | public class TenantResolutionMiddleware(RequestDelegate next, ITenantScopeFactory tenantScopeFactory) |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Invokes the middleware to ensure the tenant is initialized. |
| | | 15 | | /// </summary> |
| | | 16 | | /// <param name="context">The current HTTP context.</param> |
| | | 17 | | /// <param name="tenantResolverPipelineInvoker"></param> |
| | | 18 | | public async Task InvokeAsync(HttpContext context, ITenantResolverPipelineInvoker tenantResolverPipelineInvoker) |
| | | 19 | | { |
| | 0 | 20 | | var tenant = await tenantResolverPipelineInvoker.InvokePipelineAsync(); |
| | | 21 | | |
| | 0 | 22 | | if (tenant != null) |
| | | 23 | | { |
| | 0 | 24 | | var tenantPrefix = tenant.GetRoutePrefix(); |
| | | 25 | | |
| | 0 | 26 | | if (!string.IsNullOrWhiteSpace(tenantPrefix)) |
| | | 27 | | { |
| | 0 | 28 | | var tenantPath = $"/{tenantPrefix}"; |
| | 0 | 29 | | if (context.Request.Path.StartsWithSegments(tenantPath)) |
| | | 30 | | { |
| | 0 | 31 | | context.Request.PathBase = tenantPath; |
| | 0 | 32 | | context.Request.Path = context.Request.Path.Value![tenantPath.Length..]; |
| | | 33 | | } |
| | | 34 | | } |
| | | 35 | | } |
| | | 36 | | |
| | 0 | 37 | | await using var tenantScope = tenantScopeFactory.CreateScope(tenant); |
| | 0 | 38 | | var originalServiceProvider = context.RequestServices; |
| | 0 | 39 | | context.RequestServices = tenantScope.ServiceProvider; |
| | 0 | 40 | | await next(context); |
| | 0 | 41 | | context.RequestServices = originalServiceProvider; |
| | 0 | 42 | | } |
| | | 43 | | } |