When a single ASP.NET Core MVC application serves multiple brands, portals, or partner themes—for example, northstar vs. kestrel or a default enterprise brand with selective overrides—duplicating controllers and business logic across separate web applications quickly creates drift and maintenance drag. Equally, scattering if (brand == ...) branches throughout Razor views makes templates brittle and hard to read.

ASP.NET Core MVC solves this cleanly by combining Razor Class Libraries (RCLs) (which package precompiled Razor views, partial views, view components, and static assets into reusable assemblies) with a custom IViewLocationExpander. When resolving a view for a request, MVC calls PopulateValues(...) to include the active brand key in the view-location cache key and ExpandViewLocations(...) to probe brand-specific Razor locations before falling back to the default or shared locations.

1. Architectural Blueprint & View Resolution Flow

Plaintext

Java
Incoming Request (e.g., X-Brand: northstar or route/claim/default)
   │
   ▼
[BrandContextResolver] ── resolves normalized BrandKey (e.g., "northstar", "kestrel", or "default")
   │                      stores in HttpContext.Items
   ▼
[RazorViewEngine + BrandViewLocationExpander]
   ├─ PopulateValues(): adds "brand" -> normalized brand key to view cache key
   └─ ExpandViewLocations(): searches in priority order:
        1. Brand-specific view location (e.g., /Views/Brands/{brand}/{1}/{0}.cshtml)
        2. Brand-specific shared view (e.g., /Views/Brands/{brand}/Shared/{0}.cshtml)
        3. Standard / RCL default locations returned by base locations

Concern

Mechanism in ASP.NET Core MVC

Benefit

Brand Cache Isolation

PopulateValues(ViewLocationExpanderContext) adds "brand" to context.Values.

Prevents Brand A's resolved view path from poisoning Brand B's view location cache entry.

Selective Overrides

ExpandViewLocations(...) prepends brand-specific paths ahead of default/RCL paths.

Only customized views need brand-specific .cshtml files; unchanged views fall back automatically.

Reusable Packaging

Razor Class Libraries (RCLs) ship compiled views and assets with AssemblyPart / CompiledRazorAssemblyApplicationPart.

Multiple MVC hosts or modular features can share brand templates cleanly without copying files.

2. Brand Resolver, IViewLocationExpander, and Multi-Brand Views

Let's create a BrandContextResolver that resolves the active brand from a request header (X-Brand), query/route fallback, or configured default, and a BrandViewLocationExpander that injects the brand value into the Razor view cache key and expands search locations.

C#

C#
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Options;

public sealed class BrandOptions
{
    public const string SectionName = "Branding";

    public string DefaultBrand { get; set; } = "default";
    public string[] SupportedBrands { get; set; } = ["default", "northstar", "kestrel"];
}

public sealed class BrandContextResolver
{
    public const string BrandHeaderName = "X-Brand";
    public const string HttpContextItemKey = "__ResolvedBrandKey";

    private readonly BrandOptions _options;

    public BrandContextResolver(IOptions<BrandOptions> options)
    {
        _options = options.Value;
    }

    public string ResolveBrand(HttpContext context)
    {
        ArgumentNullException.ThrowIfNull(context);

        if (context.Items.TryGetValue(HttpContextItemKey, out object? cached) &&
            cached is string cachedBrand &&
            !string.IsNullOrWhiteSpace(cachedBrand))
        {
            return cachedBrand;
        }

        string? candidate = null;
        if (context.Request.Headers.TryGetValue(BrandHeaderName, out var headerValues) &&
            !string.IsNullOrWhiteSpace(headerValues))
        {
            candidate = headerValues.ToString().Trim().ToLowerInvariant();
        }
        else if (context.Request.Query.TryGetValue("brand", out var queryValues) &&
                 !string.IsNullOrWhiteSpace(queryValues))
        {
            candidate = queryValues.ToString().Trim().ToLowerInvariant();
        }

        string normalizedDefault = NormalizeOrDefault(_options.DefaultBrand, "default");
        string resolved = IsSupported(candidate) ? candidate! : normalizedDefault;

        context.Items[HttpContextItemKey] = resolved;
        return resolved;
    }

    private bool IsSupported(string? candidate)
    {
        if (string.IsNullOrWhiteSpace(candidate))
        {
            return false;
        }

        return _options.SupportedBrands.Any(b =>
            string.Equals(b.Trim(), candidate, StringComparison.OrdinalIgnoreCase));
    }

    private static string NormalizeOrDefault(string? value, string fallback) =>
        string.IsNullOrWhiteSpace(value) ? fallback : value.Trim().ToLowerInvariant();
}

public sealed class BrandViewLocationExpander : IViewLocationExpander
{
    private const string BrandValueKey = "brand";

    public void PopulateValues(ViewLocationExpanderContext context)
    {
        ArgumentNullException.ThrowIfNull(context);

        var resolver = context.ActionContext.HttpContext.RequestServices
            .GetRequiredService<BrandContextResolver>();

        string brand = resolver.ResolveBrand(context.ActionContext.HttpContext);
        context.Values[BrandValueKey] = brand;
    }

    public IEnumerable<string> ExpandViewLocations(
        ViewLocationExpanderContext context,
        IEnumerable<string> viewLocations)
    {
        ArgumentNullException.ThrowIfNull(context);
        ArgumentNullException.ThrowIfNull(viewLocations);

        string brand = context.Values.TryGetValue(BrandValueKey, out object? rawBrand) &&
                       rawBrand is string brandStr &&
                       !string.IsNullOrWhiteSpace(brandStr)
            ? brandStr
            : "default";

        // {0} = View Name, {1} = Controller Name, {2} = Area Name
        string[] brandLocations =
        [
            $"/Views/Brands/{brand}/{{1}}/{{0}}.cshtml",
            $"/Views/Brands/{brand}/Shared/{{0}}.cshtml",
            $"/BrandThemes/{brand}/Views/{{1}}/{{0}}.cshtml",
            $"/BrandThemes/{brand}/Views/Shared/{{0}}.cshtml"
        ];

        foreach (string location in brandLocations)
        {
            yield return location;
        }

        foreach (string location in viewLocations)
        {
            yield return location;
        }
    }
}

3. MVC Controller and ViewModel

The controller stays completely brand-agnostic: it prepares the PortalWelcomeViewModel and returns View(model). BrandViewLocationExpander determines whether a brand-specific template or the shared fallback template is rendered.

C#

C#
using Microsoft.AspNetCore.Mvc;

public sealed record PortalWelcomeViewModel(
    string BrandKey,
    string PortalTitle,
    string SupportEmail,
    DateTimeOffset GeneratedAtUtc
);

[Route("portal")]
public sealed class PortalController : Controller
{
    private readonly BrandContextResolver _brandResolver;

    public PortalController(BrandContextResolver brandResolver)
    {
        _brandResolver = brandResolver;
    }

    [HttpGet("welcome")]
    public IActionResult Welcome()
    {
        string brand = _brandResolver.ResolveBrand(HttpContext);

        string portalTitle = brand switch
        {
            "northstar" => "Northstar Enterprise Portal",
            "kestrel" => "Kestrel Commercial Hub",
            _ => "Standard Portal"
        };

        string supportEmail = brand switch
        {
            "northstar" => "[email protected]",
            "kestrel" => "[email protected]",
            _ => "[email protected]"
        };

        var vm = new PortalWelcomeViewModel(
            BrandKey: brand,
            PortalTitle: portalTitle,
            SupportEmail: supportEmail,
            GeneratedAtUtc: DateTimeOffset.UtcNow);

        return View(vm);
    }
}

4. Razor Views (Shared Fallback and Brand-Specific Overrides)

In a multi-brand setup (whether views live in a Razor Class Library or under Views/), you provide a default/fallback view (Views/Portal/Welcome.cshtml) and override specific brands (such as Views/Brands/northstar/Portal/Welcome.cshtml) without duplicating every other view in the application.

Fallback View (Views/Portal/Welcome.cshtml)

Razor CSHTML

TypeScript
@model PortalWelcomeViewModel
@{
    ViewData["Title"] = Model.PortalTitle;
}

<main class="portal-view portal-default" data-brand="@Model.BrandKey">
    <h1>@Model.PortalTitle</h1>
    <p>Active Theme Key: <strong>@Model.BrandKey</strong></p>
    <p>Contact: <span>@Model.SupportEmail</span></p>
</main>

Brand Override View (Views/Brands/northstar/Portal/Welcome.cshtml)

Razor CSHTML

TypeScript
@model PortalWelcomeViewModel
@{
    ViewData["Title"] = Model.PortalTitle;
}

<section class="portal-view portal-northstar" data-brand="@Model.BrandKey">
    <header class="brand-banner">
        <h2>NORTHSTAR EDITION</h2>
        <h1>@Model.PortalTitle</h1>
    </header>
    <p>Dedicated Northstar template rendered via custom IViewLocationExpander.</p>
    <p>Support Desk: <strong>@Model.SupportEmail</strong></p>
</section>

5. Program.cs Wiring and End-to-End Integration Testing

Application Setup (Program.cs)

Register BrandContextResolver and add BrandViewLocationExpander to RazorViewEngineOptions.ViewLocationExpanders. If you package brand views inside one or more Razor Class Libraries (RCLs), you can also add their assemblies via ConfigureApplicationPartManager(...) so compiled Razor views in those RCLs participate in view resolution.

C#

C#
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Razor;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddOptions<BrandOptions>()
    .Bind(builder.Configuration.GetSection(BrandOptions.SectionName))
    .Validate(o => !string.IsNullOrWhiteSpace(o.DefaultBrand), "DefaultBrand must be configured.")
    .ValidateOnStart();

builder.Services.AddSingleton<BrandContextResolver>();

builder.Services.AddControllersWithViews()
    .ConfigureApplicationPartManager(partManager =>
    {
        // If loading views from external Razor Class Library assemblies, register them here:
        // var rclAssembly = typeof(SomeBrandRclMarker).Assembly;
        // if (!partManager.ApplicationParts.OfType<AssemblyPart>().Any(p => p.Assembly == rclAssembly))
        // {
        //     partManager.ApplicationParts.Add(new AssemblyPart(rclAssembly));
        // }
        _ = partManager;
    });

builder.Services.Configure<RazorViewEngineOptions>(options =>
{
    options.ViewLocationExpanders.Add(new BrandViewLocationExpander());
});

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapControllers();

app.Run();

public partial class Program { }

Integration Test Verifying Brand-Specific and Fallback View Resolution (WebApplicationFactory<Program>)

C#

C#
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public sealed class MultiBrandViewLocationTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public MultiBrandViewLocationTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task WelcomeView_WithNorthstarHeader_RendersNorthstarBrandTemplate()
    {
        using HttpClient client = _factory.CreateClient();
        using var request = new HttpRequestMessage(HttpMethod.Get, "/portal/welcome");
        request.Headers.Add(BrandContextResolver.BrandHeaderName, "northstar");

        HttpResponseMessage response = await client.SendAsync(request);
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        string html = await response.Content.ReadAsStringAsync();
        Assert.Contains("NORTHSTAR EDITION", html);
        Assert.Contains("Northstar Enterprise Portal", html);
    }

    [Fact]
    public async Task WelcomeView_WithKestrelHeader_FallsBackToDefaultTemplateWithKestrelModel()
    {
        using HttpClient client = _factory.CreateClient();
        using var request = new HttpRequestMessage(HttpMethod.Get, "/portal/welcome");
        request.Headers.Add(BrandContextResolver.BrandHeaderName, "kestrel");

        HttpResponseMessage response = await client.SendAsync(request);
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        string html = await response.Content.ReadAsStringAsync();
        Assert.Contains("Kestrel Commercial Hub", html);
        Assert.Contains("Active Theme Key: <strong>kestrel</strong>", html);
    }
}

6. Conclusion

Pairing Razor Class Libraries (RCLs) with a custom IViewLocationExpander lets a single ASP.NET Core MVC codebase serve multiple brands cleanly without controller duplication or tangled conditional markup. By including the active brand key in PopulateValues(...) for accurate view-location caching and ordering brand-specific paths ahead of fallback views in ExpandViewLocations(...), you get selective per-brand customization, shared defaults, and easy reuse across applications.