Recipe 16.5 · C#
Navigation Menus from Configuration
Problem
The menu is either a Web.sitemap file with role trimming that nobody fully understands, or a master page code-behind full of if (User.IsInRole(...)) menu.Items.Add(...). Adding a page means editing code, and the menu shows links the user isn't allowed to open.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
<!-- Not to copy: Web.sitemap plus roles that drift from code -->
<siteMap>
<siteMapNode url="~/Default.aspx" title="Home">
<siteMapNode url="~/Billing/Invoices.aspx" title="Invoices"
roles="Finance,Admin" />
<siteMapNode url="~/Admin/Users.aspx" title="Users"
roles="Admin" />
</siteMapNode>
</siteMap>
The roles attribute only hides links when security trimming is switched on, and it is a second, separate list from the rules that actually protect the pages. The two drift apart.
The improved recipe
Configuration in appsettings.json:
{
"Navigation": {
"Items": [
{ "Title": "Home", "Url": "/" },
{
"Title": "Billing",
"Policy": "Finance",
"Children": [
{ "Title": "Invoices", "Url": "/invoices" },
{ "Title": "Payments", "Url": "/payments" }
]
},
{ "Title": "Users", "Url": "/admin/users", "Policy": "Admin" }
]
}
}
The options, the view component and the registration:
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace ImproveCode.Web.Navigation;
public sealed class NavItem
{
public string Title { get; set; } = "";
public string? Url { get; set; }
public string? Policy { get; set; }
public List<NavItem> Children { get; set; } = [];
}
public sealed class NavigationOptions
{
public List<NavItem> Items { get; set; } = [];
}
public sealed record MenuEntry(
string Title, string Url, bool IsActive,
IReadOnlyList<MenuEntry> Children);
public sealed class MainMenuViewComponent(
IOptionsMonitor<NavigationOptions> options,
IAuthorizationService authorization) : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
string path = HttpContext.Request.Path.Value ?? "/";
List<MenuEntry> menu = await BuildAsync(
options.CurrentValue.Items, UserClaimsPrincipal, path);
return View(menu);
}
private async Task<List<MenuEntry>> BuildAsync(
IEnumerable<NavItem> items, ClaimsPrincipal user, string path)
{
var entries = new List<MenuEntry>();
foreach (NavItem item in items)
{
if (item.Policy is not null &&
!(await authorization.AuthorizeAsync(
user, item.Policy)).Succeeded)
{
continue;
}
List<MenuEntry> children =
await BuildAsync(item.Children, user, path);
if (item.Url is null && children.Count == 0)
{
continue; // a group with nothing visible in it
}
bool active = IsActive(item.Url, path)
|| children.Exists(c => c.IsActive);
entries.Add(new MenuEntry(
item.Title, item.Url ?? "#", active, children));
}
return entries;
}
private static bool IsActive(string? url, string path)
{
if (url is null)
{
return false;
}
if (url == "/")
{
return path == "/";
}
return path.Equals(url, StringComparison.OrdinalIgnoreCase)
|| path.StartsWith(
url + "/", StringComparison.OrdinalIgnoreCase);
}
}
public static class NavigationSetup
{
public static IServiceCollection AddNavigation(
this IServiceCollection services, IConfiguration config)
{
services.AddOptions<NavigationOptions>()
.Bind(config.GetSection("Navigation"))
.Validate(
o => o.Items.Count > 0 &&
o.Items.TrueForAll(i => i.Title.Length > 0),
"Navigation needs at least one item with a title.")
.ValidateOnStart();
return services;
}
}
The view for the component:
@* Views/Shared/Components/MainMenu/Default.cshtml *@
@using ImproveCode.Web.Navigation
@model IReadOnlyList<MenuEntry>
<ul class="nav">
@foreach (MenuEntry item in Model)
{
<li class="nav-item @(item.IsActive ? "active" : "")">
<a class="nav-link" href="@item.Url">@item.Title</a>
@if (item.Children.Count > 0)
{
<ul class="sub-nav">
@foreach (MenuEntry child in item.Children)
{
<li class="@(child.IsActive ? "active" : "")">
<a href="@child.Url">@child.Title</a>
</li>
}
</ul>
}
</li>
}
</ul>
In the layout: @await Component.InvokeAsync("MainMenu").
How it works
The menu is data. Adding a page to the menu is a configuration change, reviewed like any other, and the options are validated at startup so a broken section fails the deployment instead of the first request.
Each item names an authorization policy, the same policies that protect the controllers ([Authorize(Policy = "Finance")]). The view component asks IAuthorizationService whether the current user satisfies the policy, so the menu and the page security use one rule and can't drift. A group like "Billing" disappears when none of its children are visible.
IsActive compares whole path segments, so /invoices/42 highlights "Invoices" but /invoices-archive doesn't. A parent is active when any child is, which keeps the open section highlighted.
Because the component reads IOptionsMonitor<T>.CurrentValue, menu changes in appsettings.json show up without a restart.
Variations and pitfalls
- A policy named in configuration but not registered makes
AuthorizeAsyncthrow. Add a startup check that everyPolicyin the menu exists, usingIAuthorizationPolicyProvider.GetPolicyAsync. - Hiding a link is not security. Every target still needs its own
[Authorize]or filter; the menu just stops advertising what the user can't open. - For per-tenant or user-editable menus, load the items from a table and cache them (Chapter 3). The view component doesn't change.
- Generate URLs from route names (
Url.RouteUrl) if your paths change often; plain paths are easier for administrators to read.