Middleware Sudo Code for maintaining custom or sub-domain model at. NET MVC

Published At 2026/Jan/22

DomainRoutingMiddleware – Full Documentation

DomainRoutingMiddleware

This document provides a complete technical breakdown of the DomainRoutingMiddleware used in an ASP.NET Core application. The middleware enforces domain-based access control for multi-tenant storefront systems.


Purpose of This Middleware

  • Allow full access on the main domain
  • Restrict custom domains to storefront-only routes
  • Protect admin, account, and internal routes
  • Redirect unauthorized access safely

Complete Source Code

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

public class DomainRoutingMiddleware
{
    private readonly RequestDelegate _next;

    public DomainRoutingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var host = context.Request.Host.Host.ToLower();
        var path = context.Request.Path.Value?.ToLower() ?? "/";

        bool isMainDomain = host == "www.shop-e-business.com" ||
                            host == "shop-e-business.com" ||
                            host == "localhost";

        if (!isMainDomain)
        {
            bool isAllowedPath = path == "/" ||
                                 path.StartsWith("/product/view/") ||
                                 path.StartsWith("/store/") ||
                                 IsStaticFile(path);

            if (!isAllowedPath)
            {
                var mainDomainUrl =
                    $"https://www.shop-e-business.com{path}{context.Request.QueryString}";

                context.Response.Redirect(mainDomainUrl);
                return;
            }

            if (path == "/")
            {
                // Optional internal rewrite logic
                // context.Items["CurrentShopDomain"] = host;
                // context.Request.Path = "/Shop/Storefront";
            }
        }

        await _next(context);
    }

    private bool IsStaticFile(string path)
    {
        return path.EndsWith(".css") ||
               path.EndsWith(".js") ||
               path.EndsWith(".png") ||
               path.EndsWith(".jpg") ||
               path.EndsWith(".ico") ||
               path.StartsWith("/lib/");
    }
}
    

Line-by-Line Explanation

1. Namespace Imports

Microsoft.AspNetCore.Http provides access to HTTP request and response objects.
System.Threading.Tasks enables asynchronous execution using Task.

2. Middleware Declaration

The middleware class must accept a RequestDelegate which represents the next component in the HTTP pipeline.

3. RequestDelegate Field

_next stores the reference to the next middleware. This is mandatory in ASP.NET Core middleware design.

4. Constructor

The constructor receives the next delegate via dependency injection and assigns it to the private field.

5. InvokeAsync Method

InvokeAsync is automatically executed for every HTTP request. It contains the core domain-routing logic.

6. Host & Path Extraction

  • Host determines which domain the request came from
  • Path identifies the requested URL segment
  • Both are normalized to lowercase for consistency

7. Main Domain Detection

The middleware checks if the request belongs to the official application domain or a local development environment.

8. Custom Domain Logic

If the domain is NOT the main domain, stricter rules are applied. This protects internal routes from public access.

9. Allowed Route Validation

  • Storefront root (/)
  • Product details pages
  • Store pages
  • Static assets

10. Redirection Strategy

Unauthorized access attempts are redirected to the main domain, preserving both path and query string to avoid breaking navigation.

11. Optional Internal Rewrite

Commented code allows mapping a custom domain’s root to an internal controller without exposing internal routes.

12. Static File Detection

Static assets are explicitly allowed to ensure correct UI rendering on custom domains.

13. Pipeline Continuation

await _next(context) ensures that the request continues through the remaining middleware components.


Recommended Usage

Register this middleware early in the pipeline (before MVC routing):

app.UseMiddleware<DomainRoutingMiddleware>();
    

© 2026 – Enterprise Middleware Documentation