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

gpeipman
11K 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.

References

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