ASP.NET Core

Part 2, add a controller to an ASP.NET Core MVC app

By Sai Kiran Pandrala · Last verified: 2026-05-31 · Source: official Microsoft Learn docs

At a glance
Product familyASP.NET Core
Document sourceAspnet Core Aspnetcore 10.0
Guide typeReference Guide
Skill levelIntermediate to advanced
Time15 - 60 minutes depending on environment

This page documents Part 2, add a controller to an ASP.NET Core MVC app for engineers working with ASP.NET Core. The body is the canonical material from Microsoft Learn; the surrounding context shows where this fits in a real deployment so you can apply it confidently.

Hands-on walkthrough

MVC has been around in ASP.NET land since 2009. The patterns are mature, the conventions are well-trodden, and there's still a way to mess it up. Part 2, add a controller to an ASP.NET Core MVC app is one of those topics where you read the docs, nod, and then trip on the first edge case in production. Here's how I work through it.

I broke production with this exact thing in 2021. Cost the team a 3-hour rollback window. Wouldn't recommend.

What you should have ready

Walkthrough

  1. Create or open the controller. Right-click on the Controllers folder > Add > Controller. Or do it from the CLI by hand: a controller is just a class that inherits from Controller and has action methods.
  2. Decide on action methods. Standard CRUD looks like Index (list), Details (single), Create (form), Edit (update form), Delete (remove). Stick with the convention. The MVC tooling will thank you.
  3. Wire the controller into routing. Default convention in Program.cs is app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"). If your controller doesn't show up at the URL you expect, the route map is the first thing to check.
  4. Create the views. Per controller action, a Razor view in Views/<Controller>/<Action>.cshtml. Use the View > Add Scaffolding for forms; it generates correct anti-forgery tokens automatically.
  5. Pass data via the model. Strongly-typed views with @model MyViewModel at the top. Don't use ViewBag beyond simple one-offs; it makes refactoring painful.
  6. Add validation. Data annotations on the view model: [Required], [StringLength(100)], [EmailAddress]. Client-side validation kicks in automatically with the jQuery validation scripts.
  7. Run with dotnet watch run. Hot reload picks up controller and view changes in 1-2 seconds.

How I verify MVC plumbing

Things that go wrong

  1. Anti-forgery token mismatch. If you removed the @Html.AntiForgeryToken() from a form or skipped [ValidateAntiForgeryToken] on the action, you'll see a 400 with no obvious error. Look at the Response body, the framework writes a clear message.
  2. Action name vs view file name mismatch. Razor view discovery is convention-based. Action EditDetails looks for Views/Foo/EditDetails.cshtml. Get the casing right.
  3. Tag helpers not active. Need @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers in _ViewImports.cshtml. Without it, asp-for and asp-action just render as inert attributes.
  4. Model binder silently dropping properties. If your view model has a property the form didn't post, it stays as default. If the form posts a property your model doesn't have, it's silently discarded. Test with the full payload.

Rollback

MVC changes are usually localized to a few files. Git revert is enough. If the change touched routing in Program.cs, double-check no other controller's URL changed as a side effect.

If the fix doesn't stick after a deploy, check whether your build cache is serving stale artifacts. I've been bitten by this on Azure DevOps Pipelines more times than I'd like to admit.

Operational notes

Here's the wider context, because the surface-level steps only get you to 70% of a robust deployment.

Team and runbook. Internal docs decay fast. I keep a CHANGELOG.md next to the code that touches this area, with a date and a one-line summary of every meaningful change.

Cost watch. Reserved instances and savings plans can trim 30-60% off baseline compute cost. Worth doing if your workload is steady and you can commit for a year or three.

Security pass. Never log secrets. I have caught myself logging an Authorization header twice in my career. Both times during 'just adding debug logs.' Use structured logging with redaction policies.

Observability. Add structured log fields. _logger.LogInformation("Processed {OrderId} for {UserId} in {ElapsedMs}ms", id, userId, sw.ElapsedMilliseconds); — every field is queryable in your sink.

Patterns I keep coming back to

Across many projects in ASP.NET Core, a few patterns repeat that are worth naming explicitly.

Decisions worth revisiting periodically

Some choices made early in a project age fast. I keep a list of "look at this every six months" items per project. ASP.NET Core-flavored versions look like this:

  1. SDK and framework version. Are you on the current LTS? Microsoft's support window is fixed; falling behind two majors means you're paying interest in security patches.
  2. Dependency surface. Run dotnet list package --outdated quarterly. Each outdated package is a small risk; cumulatively, large risk.
  3. Build time. If your CI builds creep past 8-10 minutes, the developer feedback loop slows enough to hurt productivity. Profile and trim.
  4. Test coverage and execution time. Coverage that climbs slowly is fine. Test suites that climb slowly toward 30 minutes is a warning sign — refactor or parallelize.
  5. Production error budget. If you're hitting your error budget consistently, slow feature work and pay down operational debt. If you're under-using your error budget, you're shipping too slowly.

Why I do it this way

Years ago I treated each topic in isolation. I'd read the docs, implement the feature, ship it, move on. The result was a lot of features that worked individually and didn't compose well. Today I default to: read the docs, sketch a diagram on paper or a digital whiteboard, identify the trust boundary, identify the failure mode, then implement. Ten extra minutes up front, hours saved down the road.

The other shift was treating tests as the design tool, not the verification tool. Writing the test first forces you to think about the API surface from the caller's perspective. By the time the test compiles, the design has been pressure-tested by your own most demanding consumer: a test that has to drive the feature without knowing the implementation.

Practical example: last month I rewrote a small reporting endpoint. The first draft was a single 60-line action method that pulled data, transformed it, and returned JSON. Tests forced me to split it into an IReportRepository, an IReportFormatter, and a thin controller. Same functionality, but now I can swap the formatter for HTML output by writing one new class and zero changes to the controller. That's the power of writing the test first.

References worth bookmarking

How to apply this in practice

Caveats and what to double-check

FAQ

Where does this part 2, add a controller to an asp.net core mvc app content come from?
It is sourced from the official Microsoft Learn documentation for ASP.NET Core. Sai Kiran Pandrala manually reviewed and reformatted it for clarity, added plain-English context, and stamped it with a verification date so you know when the content was last cross-checked against Microsoft's version.
How often is this reference updated?
Microsoft updates ASP.NET Core documentation continuously. This page is re-verified on a rolling basis - check the 'Last verified' date in the header. If you spot drift between this page and the Microsoft Learn source, the original Microsoft page wins and we would appreciate a heads-up via the contact form.
Can I use part 2, add a controller to an asp.net core mvc app information for production planning?
Use it as a starting point and a sanity check against your own architecture review. For production decisions on ASP.NET Core, always pair it with: your tenant's specific SKU and region, your compliance constraints, and Microsoft's own service health and pricing pages at the time of decision.
Why is this reference free?
HowToFixMe is ad-supported. There are no paywalls, no email signups, no signup-to-read patterns. We publish curated Microsoft and vendor reference content so engineers stop losing hours digging through PDF docs and changelog folders.
Where can I read the original Microsoft source?
On the Microsoft Learn portal under ASP.NET Core. Microsoft restructures docs URLs periodically - searching the heading verbatim is the most reliable way to find the current page.

References

Related guides worth a look while you sort this one out: