Multi-tenant ASP.NET Core 6 - Handling missing tenants

gpeipman
852 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Handling missing tenants

What to do when multi-tenant application gets request and it cannot find the tenant? Should it crash? I think the polite way is to redirect user to some page that tells what happened and perhaps gives user some guidance about how to get help or how to get started. For this let's create missing tenant middleware that redirect user to some informative page.

We start with defining tenant and tenant provider with its interface. Notice that tenant provider in this example returns null. It means that tenant was not found.

public class Tenant
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string HostName { get; set; }

    // other tenant settings
}

public interface ITenantProvider
{
    Tenant GetTenant();
}

public class DummyTenantProvider : ITenantProvider
{
    public Tenant GetTenant()
    {
        return null;
    }
}

Missing tenant middleware

Here is the middleware that is plugged to request processing pipeline. As tenant is not found then demor runner is redirected to example.com page automatically.

Click to run the .NET Core Web app.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
·using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace AspNetCoreMissingTenant
{
public class MissingTenantMiddleware
{
private readonly RequestDelegate _next;
private readonly string _missingTenantUrl;
public MissingTenantMiddleware(RequestDelegate next, string missingTenantUrl)
{
_next = next;
_missingTenantUrl = missingTenantUrl;
}
public async Task Invoke(HttpContext httpContext, ITenantProvider provider)
{
if (provider.GetTenant() == null)
{
httpContext.Response.Redirect(_missingTenantUrl);
return;
}
await _next.Invoke(httpContext);
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

References

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content