Most ASP.NET Core apps start tidy and end with 600-line controllers that validate, query, map and send emails all in one action. This post describes a structure that stays readable as an app grows: controllers that only route, services that own the rules, hand-written mapping, and folders grouped by feature. It's the structure this site runs on. Examples target ASP.NET Core on .NET 10 and C# 14.
The problem with fat controllers
A fat action does everything:
[HttpPost]
public async Task<IActionResult> Publish(int id, PublishModel model)
{
if (string.IsNullOrWhiteSpace(model.Title)) return BadRequest("Title required");
var post = await _db.Posts.Include(p => p.Tags).FirstOrDefaultAsync(p => p.Id == id);
if (post == null) return NotFound();
if (!User.IsInRole("Admin") && post.AuthorId != User.GetId()) return Forbid();
post.Title = model.Title;
post.Status = model.PublishAt > DateTime.UtcNow ? PostStatus.Scheduled : PostStatus.Published;
// … slug rules, rendering, cache clearing, email …
await _db.SaveChangesAsync();
return Ok();
}The rules can't be reused (the list page's "Publish" button needs them too), can't be unit-tested without HTTP, and the next person to edit the action has to understand all of it.
Controllers only route
Make every action one service call and one return:
[HttpPost("posts/publish")]
[Authorize(Policy = Policies.CanPublish)]
public async Task<IActionResult> Publish([FromForm] SavePostRequest request, CancellationToken ct) =>
Json(await posts.PublishAsync(request, User, ct));The controller's job is HTTP: the route, the policy, binding the request, and choosing the response type. No validation, no queries, no branching. If you're writing an if in a controller, it probably belongs in a service.
Services own the rules
The service validates, checks permissions on the specific resource, changes state, saves once, and returns a result the UI can show.
public async Task<AjaxResult> PublishAsync(SavePostRequest r, ClaimsPrincipal user, CancellationToken ct)
{
var errors = PostRules.CheckFields(r);
errors.AddRange(PostRules.CheckPublishable(r.Title, r.Slug, r.Excerpt, r.CategoryId, r.Body));
if (errors.Count > 0) return AjaxResult.FieldErrors(errors[0].Error, [.. errors]);
var post = await LoadEditableAsync(r.Id, user, ct); // resource-based permission check
if (post is null) return AjaxResult.Fail(Messages.NotAllowed);
ApplyChanges(post, r);
(post.Status, post.PublishAtUtc) = PostRules.PublishTarget(display.FromLocalInput(r.PublishAt), clock.UtcNow);
await db.SaveChangesAsync(ct);
await cache.EvictPostsAsync(ct);
return AjaxResult.Ok(Messages.Published, SavedData(post));
}Three habits make services pleasant to live with:
- Pure rules in static classes.
PostRules.PublishTarget(date, now)has no database and no HTTP, so a unit test is three lines. - Separate reads from writes.
IPostServicechanges things;IPostQueryServicereturns view models withAsNoTrackingprojections. Read code stays fast and write code stays careful. - One
SaveChangesAsyncper use case, so a use case either happens completely or not at all.
Never pass entities to views
Views get view models: small record types with exactly what the page shows.
public sealed record PostCardVm(string Slug, string Title, string Excerpt, string Topic, DateTime? PublishedAt);Entities in views leak lazy-loading surprises, over-fetching and accidental edits. A record makes the page's needs explicit and keeps queries honest.
Map by hand
Mapping libraries hide what's copied where, and errors show up at runtime. Hand-written mapping is a few lines, checked by the compiler, and reusable inside queries:
public static class PostMappings
{
public static readonly Expression<Func<Post, PostCardVm>> ToCard =
p => new PostCardVm(p.Slug, p.Title, p.Excerpt, p.Category!.Name, p.PublishAtUtc);
}
var cards = await db.Posts.Where(PostMappings.IsPublic).Select(PostMappings.ToCard).ToListAsync(ct);Because ToCard is an expression, EF Core translates it to SQL and selects only those columns.
Group by feature, inside each layer
Two common layouts:
- By type: all controllers in one folder, all services in another. Simple, but one feature is spread across the tree.
- By feature: everything about posts together.
A practical middle ground keeps the layers as folders, and groups by feature inside each:
Controllers/Admin/PostsController.cs
Services/Posts/IPostService.cs
Services/Posts/PostService.cs
Services/Posts/PostRules.cs
Models/Requests/Admin/SavePostRequest.cs
Models/ViewModels/Posts/PostCardVm.cs
Views/Admin/Posts/Edit.cshtml
wwwroot/js/pages/admin/post-edit.jsThe layer tells you what kind of code a file is; the feature folder tells you what it's about. Adding a feature means adding one folder in each layer, and deleting one means removing them.
Return one result shape
For JSON endpoints, return one shape everywhere:
public sealed record AjaxResult(bool Success, string? Message = null, object? Data = null,
IReadOnlyDictionary<string, string[]>? Errors = null);The browser shows Message as a toast and puts Errors next to the matching form fields. One small JavaScript helper handles every form on the site.
Rules worth writing down
Structure decays unless the rules are explicit. A short "ground rules" file in the repository helps every contributor, human or AI coding agent:
- Controllers route only: one service call, then return.
- Only services touch the
DbContext. - Views receive view models, never entities.
- Status changes go through one service.
- Keep files under about 300 lines; split before 500.
Wrapping up
Thin controllers, services that own the rules, pure rule classes, view models, hand-written mapping and feature folders inside layers. None of it is clever, and that's the point: a year from now, anyone can open the app, find the posts feature in four predictable places, and change it with confidence.