ASP.NET Core

Custom IViewLocationExpander and Multi-Brand Razor Class Libraries in ASP.NET Core MVC

C# Corner Sardar Mudassar Ali Khan
ASP.NET Core

A custom IViewLocationExpander lets one ASP.NET Core MVC application serve several brands without duplicating controllers or markup. The article shows how to make the brand part of the view-location cache key and probe brand-specific Razor paths before the shared fallbacks.

Key points

  • PopulateValues() writes the normalized brand key into context.Values, so each brand gets its own view-location cache entry.
  • ExpandViewLocations() probes brand paths such as /Views/Brands/{brand}/{1}/{0}.cshtml before any default location runs.
  • BrandContextResolver checks the X-Brand header, then ?brand=, then falls back to BrandOptions.DefaultBrand.
  • Views compiled into Razor Class Libraries join resolution when registered as an AssemblyPart via ConfigureApplicationPartManager.
  • Unsupported brand values silently resolve to the configured default instead of failing the request.
  • WebApplicationFactory<Program> tests assert both a brand-specific render and the shared fallback output.

Why it matters

Most teams reach for a theme engine or duplicate controllers when a second brand appears, but Razor's view engine already exposes this hook and adding a resolver plus one expander costs little. Teams serving several partners keep a single controller and a shared fallback, customizing only the pages that actually differ.

Two things deserve a check before copying it. A brand key taken from an X-Brand header is user-controlled, so validate it against an allowlist before it selects a template, and keep per-brand content authorization separate. Then watch the view-location cache: every value PopulateValues() adds becomes a cache dimension, and the order in ExpandViewLocations() decides which file wins.

Real-world use

  • A single enterprise portal serving several brands where only a handful of pages are customized.
  • Partner or reseller themes that must keep shared fallback views for everything else.
  • Brand templates packaged in Razor Class Libraries and reused by more than one MVC host.

This summary was generated by the agent from the original post on C# Corner. The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message