Fast. Simple. No meetings. No delays.
Home / Blog / .NET / .NET API Development: Practices That Keep Services Maintainable

.NET API Development: Practices That Keep Services Maintainable

Project structure, validation, error handling, logging and versioning habits that keep a .NET API maintainable as it grows.

Cover graphic for the article: .NET API Development: Practices That Keep Services Maintainable

Sound .NET API best practices come down to a few habits: organise code around features rather than technical layers, validate at the boundary, return one consistent error shape, log with correlation, authorise with policies, version deliberately and test at more than one level. Applied early, they keep an ASP.NET Core API cheap to change.

The advice below is version-agnostic. Names of attributes and helpers have been stable across recent .NET releases, but confirm details against the current Microsoft documentation for the version you target.

.NET API best practices: structure for change

Most API projects start with folders named Controllers, Services, Repositories and Models. That works for a month or two. As the API grows, a single feature such as orders is scattered across four folders, and every change touches all of them.

A more durable approach is to group by feature or capability: an Orders folder holding its endpoints, request and response types, validators and handlers. Shared infrastructure sits in a separate area. Some points to settle early:

  • Keep endpoints thin. A controller action or minimal-API handler should translate HTTP into a call and back, nothing more.
  • Put business rules in plain classes that do not reference HTTP types, so they can be tested without a web host.
  • Do not expose database entities. Use separate request and response types, so a column change does not silently change your public contract.
  • Split projects only when you must. A single project with clear folders beats five projects with circular-feeling references. Add a separate class library when a second consumer appears, such as a worker service.

Whether you use controllers or minimal endpoints matters less than being consistent. Pick one style per codebase and document the reason in the README.

Validation and model binding

Treat every request as untrusted. The framework binds JSON to your types, but binding only tells you the shape arrived, not that the values make sense.

  1. Mark required members explicitly and avoid nullable ambiguity in request types.
  2. Validate ranges, lengths, formats and cross-field rules in one place per request type, whether through data annotations or a validation library.
  3. Reject unknown or malformed input with a client error, never let it reach the database layer.
  4. Validate business rules that need data (for example, a stock check) in the handler and return a clear conflict or validation error.

Beware over-posting: if you bind directly to an entity, a client can set fields you never intended, like an IsAdmin flag. Dedicated request types prevent this by design.

Consistent error responses

Clients, whether a mobile app or another team, should be able to handle every failure the same way. The usual answer is the standard problem-details format, a small JSON shape with a type, title, status, detail and optional extension fields. ASP.NET Core has built-in support for producing it, and recent versions give you hooks to turn unhandled exceptions into that shape in one central place.

Rules that pay off:

  • One global exception handler. Controllers should not contain try/catch blocks for routine failures.
  • Use correct status codes: 400 or 422 for invalid input, 401 for unauthenticated, 403 for forbidden, 404 for missing, 409 for conflicts, and 500 only for genuine server faults.
  • Never leak stack traces, SQL text or internal hostnames in production responses.
  • Include a trace identifier in the error body so support can find the matching log entry.

Logging and tracing

Use the built-in logging abstraction with structured logging, writing properties rather than concatenated strings, so you can filter by order ID or user ID later. Decide a level policy up front: information for business events, warning for recoverable oddities, error for failures someone must look at.

Add a correlation or trace ID to every request and pass it on to downstream calls. If you run more than one service, adopt OpenTelemetry-style tracing so a request can be followed across boundaries. Avoid logging secrets, tokens, full card numbers or personal data; review log output the same way you review code. Health-check endpoints for liveness and readiness make deployments and monitoring far less painful. For a broader view on service design, see designing scalable, maintainable APIs for business systems.

Authentication and policies

Do not write your own token handling. Use the framework's authentication middleware with a standard scheme, typically JWT bearer tokens issued by an identity provider, or cookies for browser-only apps. Then use authorisation policies instead of scattering role strings across endpoints:

  • Define named policies such as CanApproveInvoices once, and reference them on endpoints.
  • Do resource-based checks (does this user own this record?) in the handler where the resource is loaded.
  • Require authorisation by default and opt endpoints out, rather than the reverse. A forgotten attribute should fail closed.
  • Keep secrets in a secret store or environment configuration, never in source control.

Rate limiting, CORS configuration and HTTPS enforcement belong in this layer too. Our guide to secure API development for SaaS products goes deeper on threat thinking.

Versioning

You will change your API, and someone will depend on the old behaviour. Decide the versioning policy before the first external consumer appears. Common choices are a URL segment, a header or a query parameter; URL segments are the easiest for partners to understand and for you to route and monitor. Libraries exist for ASP.NET Core that handle version routing and reporting of supported versions.

More important than the mechanism is the policy: additive changes (new optional fields, new endpoints) should not need a new version; removing or renaming fields, changing types or changing meaning does. Announce deprecations in writing, add a deprecation signal in responses, and measure which clients still call the old version before removing it.

Testing strategy

Aim for a mix rather than one dominant style:

LevelWhat it coversTypical tooling
UnitBusiness rules, validators, mappingxUnit or NUnit, plain classes
IntegrationEndpoint through to a real databaseIn-process test host, disposable database container
ContractResponse shapes clients depend onSchema or snapshot comparison
SmokeDeployed environment is aliveHealth checks, one or two scripted calls

Integration tests with a real database engine catch more than in-memory substitutes, which can behave differently from production. Run them in your pipeline on every pull request.

Putting it together

Start with feature-based structure, one error format and structured logging, because these are painful to retrofit. Add policies, versioning and layered tests as the API gains consumers. If you are choosing between .NET and other stacks, the comparison of ASP.NET Core and Laravel may help, and teams planning a project with a Danish company can read about how we approach software development for Denmark.

Frequently asked questions

How should I structure a .NET Web API project?

Group code by feature rather than technical layer, so an Orders folder holds its endpoints, request types, validators and handlers together. Keep endpoints thin, put business rules in plain classes, use separate request and response types instead of database entities, and split into extra projects only when a second consumer needs shared code.

What is a problem-details response?

It is a standard JSON error format with fields such as type, title, status and detail, plus optional extensions like a trace identifier. ASP.NET Core can produce it, so every failure from your API looks the same. Clients handle errors once, and support staff can match a response to a log entry.

How do I version an API in .NET?

Pick a mechanism, commonly a URL segment such as /v1/, and use a versioning library to route and report supported versions. Define a policy: additive changes need no new version, breaking changes do. Announce deprecations, track which clients still use old versions, and remove them only after that usage ends.

Related articles

🚀 Start Now