skip to content

In ASP.NET Core MVC, how would an IViewLocationExpander make a white-label listings site look for agency-specific views first, and why does PopulateValues matter?

level: seniorimportance: nice to knowfreq 22%

answer

  1. RazorViewEngineOptions.ViewLocationExpanders
  2. PopulateValues then ExpandViewLocations
  3. Values are part of the lookup cache key
  4. ExpandViewLocations runs only on a cache miss
  5. {0} view, {1} controller, {2} area

basics

~10 s

Implement IViewLocationExpander: PopulateValues stores the agency in context.Values, and ExpandViewLocations returns agency paths before the defaults. Register it in RazorViewEngineOptions.ViewLocationExpanders. Skipping the Values entry makes the lookup cache serve one agency's views to all.

solid answer

~40 s

The Razor view engine asks each registered `IViewLocationExpander` two things. First `PopulateValues(ViewLocationExpanderContext)`, where you add whatever varies the lookup, for example `context.Values["agency"] = "harbour"` taken from the host name or a route value. Those values, together with the view, controller and area names and the main-page flag, form the key of the engine's view lookup cache. Only on a cache miss does the engine call `ExpandViewLocations(context, viewLocations)`, where you return `/Agencies/{agency}/Views/{1}/{0}.cshtml` and `/Agencies/{agency}/Views/Shared/{0}.cshtml` ahead of the default locations. Register it with `builder.Services.Configure<RazorViewEngineOptions>(o => o.ViewLocationExpanders.Add(new AgencyViewLocationExpander()))` or `AddRazorOptions`. The classic bug is reading the agency inside `ExpandViewLocations` without putting it in `Values`: the first agency's resolved path is cached and every other agency gets its views.

code

csharp · 12 lines
csharp
// Bug: the agency is not in Values, so the lookup cache ignores it
public sealed class BrokenAgencyExpander : IViewLocationExpander
{
    public void PopulateValues(ViewLocationExpanderContext context) { }

    public IEnumerable<string> ExpandViewLocations(
        ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        var agency = context.ActionContext.HttpContext.Request.Host.Host.Split('.')[0];
        return viewLocations.Prepend($"/Agencies/{agency}/Views/{{1}}/{{0}}.cshtml");
    }
}

go deeper

for a junior

Recall that MVC searches fixed folders for views and that an IViewLocationExpander can add more locations.

for a middle

Explain the two methods, the {0}/{1}/{2} placeholders and how to register an expander through RazorViewEngineOptions.

for a senior

Prevent cross-tenant view leaks by putting every varying input in Values, keep cardinality low, and test hosts in sequence.

for a principal

Decide between per-tenant view overrides, theming through CSS and data, or separate deployments as the number of white-label customers grows.

## The requirement A listings platform hosts several estate agencies on one ASP.NET Core MVC app: `harbour.homes.example`, `meadow.homes.example`. Most views are shared, but some agencies need their own `Listings/Details.cshtml` or their own shared `_Layout.cshtml`. Controllers should keep returning `View()`; the **view engine** should decide where to look. ## The extension point `IViewLocationExpander` (namespace `Microsoft.AspNetCore.Mvc.Razor`) has two methods: ```csharp public sealed class AgencyViewLocationExpander : IViewLocationExpander { public void PopulateValues(ViewLocationExpanderContext context) { var host = context.ActionContext.HttpContext.Request.Host.Host; context.Values["agency"] = host.Split('.')[0]; // part of the cache key } public IEnumerable<string> ExpandViewLocations( ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { if (context.Values.TryGetValue("agency", out var agency) && agency is not null) { yield return $"/Agencies/{agency}/Views/{{1}}/{{0}}.cshtml"; yield return $"/Agencies/{agency}/Views/Shared/{{0}}.cshtml"; } foreach (var location in viewLocations) yield return location; } } ``` In the returned formats, `{0}` is the view name, `{1}` the controller name and `{2}` the area name, exactly as in `ViewLocationFormats`. The doubled braces in the interpolated strings produce literal `{1}` and `{0}` for the engine to fill. Register it once: ```csharp builder.Services.AddControllersWithViews() .AddRazorOptions(o => o.ViewLocationExpanders.Add(new AgencyViewLocationExpander())); ``` ## Why PopulateValues matters: the lookup cache Finding a view is not free, so `RazorViewEngine` caches the result of each lookup. In the source, the cache key (`ViewLocationCacheKey`) is built from: - the view name, - the controller name, - the area name, - the Razor page name, - whether it is a main page or a partial, - and the dictionary of **expander values** filled by `PopulateValues`. The sequence per lookup is: 1. Every expander's `PopulateValues` runs. 2. The engine builds the key and checks the cache. 3. **Only on a miss** does it call each expander's `ExpandViewLocations` in turn and search the resulting locations. 4. The result, found or not found, is cached under that key. The interface's own documentation says it: the populated values determine the cache key, and if they are identical to last time, the cached result is used. So if `ExpandViewLocations` reads the host directly and `PopulateValues` does nothing, the first request, say from Harbour, caches `/Agencies/harbour/Views/Listings/Details.cshtml`, and Meadow's visitors get Harbour's branding for as long as that entry stays cached; it has a 20-minute sliding expiration, so steady traffic keeps it alive indefinitely. Everything that changes the result must be in `Values`. ## Design guidance - **Keep `Values` low-cardinality.** Each distinct value multiplies cache entries; an agency key or a theme name is fine, a user id is not. - **Keep expanders cheap and stateless.** They live in the options as a single instance and run on every lookup. - **Order matters.** Expanders run in registration order, each receiving the previous one's locations, so a theme expander and a feature-folder expander can be chained. - **Static changes do not need an expander.** If the extra location never depends on the request, such as moving to feature folders, add a format to `RazorViewEngineOptions.ViewLocationFormats` instead. - **Partials and layouts use the same path.** A layout referenced as `_Layout` and partials referenced by name go through the expander too, so an agency-specific `_Layout.cshtml` is picked up without code changes. ## Alternatives worth naming An expander is not the only way to brand a white-label site. Many differences are better expressed as **data** (logo, colours, contact details in a per-agency settings record) or **CSS** (a theme stylesheet chosen in the layout), which keep one set of views. View overrides earn their place when the markup itself differs, such as an agency that requires an extra legal block on every listing. Keeping overrides rare keeps the number of view combinations, and the testing effort, under control. ## Where the values come from `PopulateValues` receives the full `ActionContext`, so the varying input can be the host name, a route value such as `{agency}`, a claim on `HttpContext.User`, or the current culture. Pick the source the rest of the app already trusts for tenant resolution; if a middleware has resolved the tenant into `HttpContext.Items` or a scoped service, read it from there so views and data access can never disagree about which agency a request belongs to. ## Testing Write one integration test per agency host with `WebApplicationFactory`, requesting the same page with different `Host` headers, and assert on agency-specific markup. Request Harbour **then** Meadow in one test: that ordering is what exposes a missing `Values` entry.

  • When would you edit ViewLocationFormats instead of writing an expander?
    When the extra locations never depend on the request, for example moving views into `/Features/{1}/{0}.cshtml`. Inserting formats into `RazorViewEngineOptions.ViewLocationFormats` is simpler and has no per-lookup cost; an expander is for locations that vary by tenant, theme, device or culture.
  • Why must values put in context.Values be low-cardinality?
    Each distinct combination of expander values is a separate entry in the view lookup cache. An agency or theme key yields a handful of entries; a per-user value would create entries without bound and defeat the cache.

The expander is a librarian with a lookup card index. PopulateValues writes which branch's collection the reader belongs to on the card; the librarian only walks the shelves when no card matches. Forget to write the branch, and the next reader is handed the first reader's book from the index.

  • ExpandViewLocations runs on every request, so reading the host there is enough.
  • PopulateValues is optional bookkeeping with no effect on which view is served.
  • An expander replaces the default locations unless it calls the base class.
  • Putting the user id in context.Values is a good way to personalise views.
  • Expanders only affect full views; layouts and partials ignore them.