Recipe 16.1 · C#
Replacing the BasePage with Filters
Problem
Every page in the application inherits from a BasePage class. It checks that the user is logged in, loads the user's permissions, decides whether this page is allowed, writes an audit record and sets the culture. It works, but it runs everything on every page whether the page needs it or not, it's impossible to test without a web server, and every new concern makes it longer.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: one base class doing everything.
public class BasePage : System.Web.UI.Page
{
protected AppUser CurrentUser;
protected override void OnInit(EventArgs e)
{
CurrentUser = Session["User"] as AppUser;
if (CurrentUser == null)
Response.Redirect("~/Login.aspx?ReturnUrl=" +
Request.RawUrl);
string page = Path.GetFileName(Request.Path);
if (!Security.CanView(CurrentUser.UserId, page))
Response.Redirect("~/NoAccess.aspx");
Thread.CurrentThread.CurrentCulture =
new CultureInfo(CurrentUser.Culture);
AuditDb.LogPageView(CurrentUser.UserId, page);
base.OnInit(e);
}
}
The permission check is keyed on the file name, so renaming a page breaks security. The audit write runs synchronously against the database on every request, including postbacks. And because the user lives in session, a recycled app pool logs everyone out.
The improved recipe
In ASP.NET Core, each job goes to the part of the pipeline built for it. Authentication and "is the user logged in" become a fallback authorization policy. Per-page permissions become an authorization filter. Auditing becomes an action filter. A base controller remains, but it holds only small conveniences.
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
namespace ImproveCode.Web.Filters;
public interface IPermissionService
{
Task<bool> HasPermissionAsync(
ClaimsPrincipal user, string permission);
}
public sealed class ClaimsPermissionService : IPermissionService
{
public Task<bool> HasPermissionAsync(
ClaimsPrincipal user, string permission) =>
Task.FromResult(user.HasClaim("permission", permission));
}
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Method,
AllowMultiple = true)]
public sealed class RequirePermissionAttribute(string permission)
: Attribute, IAsyncAuthorizationFilter
{
public string Permission { get; } = permission;
public async Task OnAuthorizationAsync(
AuthorizationFilterContext context)
{
ClaimsPrincipal user = context.HttpContext.User;
if (user.Identity?.IsAuthenticated != true)
{
context.Result = new ChallengeResult();
return;
}
var permissions = context.HttpContext.RequestServices
.GetRequiredService<IPermissionService>();
if (!await permissions.HasPermissionAsync(user, Permission))
{
context.Result = new ForbidResult();
}
}
}
The audit filter runs around every action and logs instead of writing to a table inline:
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
namespace ImproveCode.Web.Filters;
public sealed class PageAuditFilter(ILogger<PageAuditFilter> logger)
: IAsyncActionFilter
{
public async Task OnActionExecutionAsync(
ActionExecutingContext context, ActionExecutionDelegate next)
{
long started = Stopwatch.GetTimestamp();
ActionExecutedContext executed = await next();
logger.LogInformation(
"Action {Action} by {User} returned {Result} in {Ms:0} ms",
context.ActionDescriptor.DisplayName,
context.HttpContext.User.Identity?.Name ?? "(anonymous)",
executed.Result?.GetType().Name ?? "(none)",
Stopwatch.GetElapsedTime(started).TotalMilliseconds);
}
}
A thin base controller and the registration:
using System;
using System.Security.Claims;
using ImproveCode.Web.Filters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
namespace ImproveCode.Web;
public abstract class AppController : Controller
{
protected string CurrentUserId =>
User.FindFirstValue(ClaimTypes.NameIdentifier)
?? throw new InvalidOperationException("No signed-in user.");
protected IActionResult RedirectToLocal(string? returnUrl) =>
Url.IsLocalUrl(returnUrl)
? Redirect(returnUrl)
: RedirectToAction("Index", "Home");
}
public static class MvcSetup
{
public static IServiceCollection AddAppMvc(
this IServiceCollection services)
{
services.AddControllersWithViews(options =>
{
options.Filters.Add<PageAuditFilter>();
});
services.AddAuthorizationBuilder()
.SetFallbackPolicy(new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build())
.AddPolicy("Finance", p => p.RequireRole("Finance"))
.AddPolicy("Admin", p => p.RequireRole("Admin"));
services.AddSingleton<IPermissionService,
ClaimsPermissionService>();
return services;
}
}
Usage snippet:
[RequirePermission("Invoices.View")]
public async Task<IActionResult> Index(int page = 1) { /* ... */ }
How it works
The fallback policy applies to every endpoint that has no authorization attribute of its own, so a new controller is protected by default. That reverses the Web Forms habit of forgetting to inherit from BasePage on one page and leaving it open. Pages that must be public, such as the login page, opt out with [AllowAnonymous].
RequirePermissionAttribute is an authorization filter, which runs before model binding and before the action. It names the permission, not the file, so renaming a controller doesn't change who can see it. Returning ChallengeResult sends an anonymous user to sign in; ForbidResult gives a signed-in user without the permission a 403. The filter resolves IPermissionService from the request's services, so the real implementation can query a database and cache the result (Chapter 3) without the attribute knowing.
PageAuditFilter is registered globally, so it wraps every action. It awaits next(), measures the elapsed time and logs a structured event. If you need an audit table for compliance, have a logging sink or a background queue (Chapter 14) write it, not the request thread.
Culture, which the BasePage set by hand, is handled by the built-in request localization middleware (app.UseRequestLocalization()), and errors by the exception handler middleware from Chapter 5.
Variations and pitfalls
- Keep the base controller thin. When it starts loading data in its constructor or overriding
OnActionExecuting, you are rebuildingBasePage. Put behavior in filters and services; put only tiny helpers in the base class. - Razor Pages use page filters (
IAsyncPageFilter) and work best with policies:[Authorize(Policy = "Finance")]. For permission-per-page schemes across MVC, Razor Pages and minimal APIs, write anIAuthorizationHandlerwith a custom requirement instead of a filter. ClaimsPermissionServicereads permissions from claims, which suits small permission sets. With hundreds of permissions, don't stuff them into the cookie; look them up and cache them.- Filters registered with
options.Filters.Add<T>()are created per request through dependency injection, so constructor injection works. Attributes likeRequirePermissionare created once, which is why the service is resolved inside the method.