Here are 50 .NET 10 tips you can apply to your own project today, from your solution file all the way down to your EF Core queries. Every tip is written for .NET 10, C# 14 and EF Core 10, comes with a short code sample where code helps, and links to a full guide if you want to go deeper.
I picked these from the problems I keep running into in real .NET projects, and none of them needs a big rewrite. Juniors can follow every tip as it is, and seniors can use the list as a checklist for their next code review.
One date to know first: .NET 8 and .NET 9 both reached end of support on November 10, 2026. If your project still runs on either of them, it no longer gets security fixes, and that is why it is tip number one.
I also made a 13-minute video that runs through all 50 tips quickly. This article is the longer version, with code and the reason behind each tip.
What Should You Fix in Your Project Setup First?
Start with the things that affect every file and every developer on the team.
1. Upgrade to .NET 10
.NET 10 is a Long Term Support (LTS) release, so Microsoft patches it until November 14, 2028. For most apps, the upgrade starts with one line in your project file.
<TargetFramework>net10.0</TargetFramework>Then update your Microsoft packages to 10.x and run your tests. All dates are on the official .NET support policy.
2. Move Your Solution to .slnx
The new .slnx solution format is a short XML file that you can actually read in a pull request. Since .NET 10, dotnet new sln creates it by default. To convert an existing solution, run this in the folder that has your .sln file.
dotnet sln migrateI wrote a full guide on this: .slnx vs .sln in .NET 10.
3. Share Settings With Directory.Build.props
Put the settings all your projects share in a Directory.Build.props file at the root, and every project below that folder picks them up automatically.
<Project> <PropertyGroup> <TargetFramework>net10.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup></Project>4. Use Central Package Management
Central Package Management does the same thing for NuGet versions. All versions live in one Directory.Packages.props file, so two projects can never end up on different versions of the same package.
<Project> <PropertyGroup> <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally> </PropertyGroup> <ItemGroup> <PackageVersion Include="Serilog.AspNetCore" Version="11.0.0" /> </ItemGroup></Project>Your project files then reference packages without a version.
5. Treat Nullable Warnings as Errors
A lot of NullReferenceException crashes in production started as a yellow warning that somebody scrolled past. Add this line to your Directory.Build.props, and the build fails instead.
<WarningsAsErrors>Nullable</WarningsAsErrors>On an older codebase this can produce hundreds of errors, so turn it on for new projects first.
6. Read the NuGet Audit Warnings
Warnings NU1901 to NU1904 mean a package you use has a known security vulnerability. In .NET 10, this check also covers transitive packages, which are the packages your packages pull in (NuGet auditing docs). You can list them any time:
dotnet list package --vulnerable --include-transitive7. Check the License Before Adding a Package
A few popular .NET libraries moved to commercial licenses in the last two years, including MediatR, AutoMapper and MassTransit. Check the license on NuGet before you add a package, because removing it from fifty files later is much harder. If you only used MediatR for simple request handling, you can build your own CQRS dispatcher.
8. Keep Secrets in User Secrets
Never commit API keys or connection strings to Git. While you develop, keep them in user secrets, which live outside the repository.
dotnet user-secrets initdotnet user-secrets set "Stripe:ApiKey" "your-key-here"ASP.NET Core reads them automatically in Development. More in my guide to appsettings, environment variables and user secrets.
Which C# Features Make Everyday Code Shorter?
You can start using these in the next class you write.
9. Use Records for DTOs
A record gives you properties, a constructor and value equality in one line, which is everything a DTO (Data Transfer Object) needs.
public record ProductDto(Guid Id, string Name, decimal Price);10. Use Primary Constructors for Services
With a primary constructor, you list your dependencies right after the class name, and the private fields and constructor body go away.
public class OrderService(AppDbContext db, ILogger<OrderService> logger){ public async Task<Order?> GetAsync(int id, CancellationToken ct) => await db.Orders.FindAsync([id], ct);}11. Use Collection Expressions
Square brackets create a list or an array, like List<string> tags = []; or int[] ids = [1, 2, 3];.
12. Check for Null With “is null”
is null and is not null read like plain English, and they always do a real null check, even if a type overloads the == operator.
13. Replace Long if-else Chains With Switch Expressions
When you map one value to another, a switch expression turns a long if-else chain into a few lines, and the compiler warns you if you miss a case.
var label = status switch{ OrderStatus.Pending => "Waiting for payment", OrderStatus.Shipped => "On the way", OrderStatus.Delivered => "Delivered", _ => "Unknown"};14. Use Raw String Literals for JSON and SQL
Wrap text in three double quotes, and you never have to escape a quote again.
var json = """ { "name": "Keyboard", "price": 49.99 } """;15. Mark Must-Have Properties as required
If a property must always be set, mark it required. The code will not compile until whoever creates the object sets it.
public class User{ public required string Email { get; init; }}16. Use Null-Conditional Assignment (C# 14)
C# 14 lets you use ?. on the left side of an assignment, so the value is only set when the object is not null. See What’s new in C# 14.
// Beforeif (customer is not null) { customer.Order = GetCurrentOrder(); }
// C# 14customer?.Order = GetCurrentOrder();17. Store Dates in UTC and Use TimeProvider
Store every date in UTC with DateTimeOffset, and inject TimeProvider instead of calling DateTime.Now, so your tests can set the clock.
builder.Services.AddSingleton(TimeProvider.System);
public class TrialService(TimeProvider time){ public DateTimeOffset TrialEnds() => time.GetUtcNow().AddDays(14);}What Async Mistakes Slow Down a .NET API?
A few small async mistakes can make an API slow under load or even crash it. My 20 tips from a senior .NET developer covers async in more depth.
18. Never Call .Result or .Wait()
.Result and .Wait() block a thread while it waits. Under load, blocked threads pile up and your API slows down for no clear reason.
// Bad: blocks a threadvar user = GetUserAsync(id).Result;
// Good: frees the thread while waitingvar user = await GetUserAsync(id);19. Pass the CancellationToken All the Way Down
When a user closes the browser tab, ASP.NET Core cancels the request’s token. Pass that token to your database call, and the query stops too.
app.MapGet("/products/{id}", async (int id, AppDbContext db, CancellationToken ct) => await db.Products.FindAsync([id], ct));20. Avoid async void
If an async void method throws, nobody can catch the exception, and it can crash the whole process. Return Task instead, and keep async void for event handlers only.
21. Run Independent Calls With Task.WhenAll
When two calls don’t depend on each other, start both and wait for them together. Two 2-second calls then finish in about 2 seconds instead of 4.
var ordersTask = ordersClient.GetAsync(userId, ct);var invoicesTask = invoicesClient.GetAsync(userId, ct);await Task.WhenAll(ordersTask, invoicesTask);One thing to watch: a single DbContext cannot run two queries at the same time, so use this for HTTP calls or separate contexts.
22. Use Task.Delay Instead of Thread.Sleep
Thread.Sleep holds the thread for the whole wait, while await Task.Delay(1000, ct) gives it back and can be cancelled.
How Do You Avoid Common Dependency Injection Bugs?
Dependency injection (DI) is how ASP.NET Core creates services and passes them to your classes.
23. Never Inject a Scoped Service Into a Singleton
A singleton lives for the whole app, while a scoped service like your DbContext should live for one request. A singleton that takes a DbContext keeps that one context alive forever, which causes stale data and threading errors. ASP.NET Core catches this at startup in Development, so don’t switch that check off. See Singleton vs Scoped vs Transient.
24. Stop Pulling Services From IServiceProvider
Calling provider.GetRequiredService<T>() inside your classes hides what they depend on. Ask for services in the constructor, so the dependencies are visible.
Dependency Injection in ASP.NET Core - The Complete .NET 10 Guide
How DI works in ASP.NET Core, registration patterns, and the mistakes to avoid.
What Should Every ASP.NET Core API Have From Day One?
These are the defaults I add to every new Web API before the first real endpoint.
25. Cache With HybridCache
HybridCache (from the Microsoft.Extensions.Caching.Hybrid package) keeps data in memory, can also use Redis, and makes sure only one request rebuilds an expired entry while the others wait for it.
builder.Services.AddHybridCache();
var product = await cache.GetOrCreateAsync($"product:{id}", async token => await db.Products.FindAsync([id], token), cancellationToken: ct);Full walkthrough: HybridCache in ASP.NET Core, and the API is on Microsoft Learn.
26. Group Your Routes With MapGroup
MapGroup sets the shared route prefix once, and you can add authorization to the whole group in one place.
var products = app.MapGroup("/api/products").RequireAuthorization();products.MapGet("/", GetAll);products.MapGet("/{id}", GetById);27. Return TypedResults
With TypedResults, the OpenAPI document knows exactly which responses each endpoint can return, without any extra attributes.
static async Task<Results<Ok<Product>, NotFound>> GetById(int id, AppDbContext db, CancellationToken ct) => await db.Products.FindAsync([id], ct) is { } p ? TypedResults.Ok(p) : TypedResults.NotFound();28. Add ProblemDetails
builder.Services.AddProblemDetails() makes every error from your API use the same JSON shape (RFC 9457), so your frontend can handle all errors with the same code. More in ProblemDetails in ASP.NET Core.
29. Use One Global Exception Handler
Write one class that implements IExceptionHandler, register it next to AddProblemDetails from the previous tip, and delete the try-catch blocks you copied into every endpoint. Every unhandled exception is then logged once and returns a clean ProblemDetails response.
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger, IProblemDetailsService problemDetails) : IExceptionHandler{ public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct) { logger.LogError(exception, "Unhandled exception"); context.Response.StatusCode = StatusCodes.Status500InternalServerError; return await problemDetails.TryWriteAsync(new() { HttpContext = context, Exception = exception }); }}builder.Services.AddExceptionHandler<GlobalExceptionHandler>();app.UseExceptionHandler();Global Exception Handling in ASP.NET Core - The Complete Guide for .NET 10
IExceptionHandler, ProblemDetails and handling different exception types cleanly.
30. Turn On Built-In Validation (.NET 10)
New in .NET 10, call AddValidation, and Minimal APIs check your data annotation attributes before your handler runs. Invalid requests get a 400 with the field errors.
builder.Services.AddValidation();
public record CreateUserRequest([Required] string Name, [EmailAddress] string Email);Details are on Microsoft Learn.
31. Use the Options Pattern With ValidateOnStart
Bind your settings to a typed class and validate them at startup, so a missing setting stops the app right away instead of failing on the first email.
builder.Services.AddOptions<SmtpOptions>() .BindConfiguration("Smtp") .ValidateDataAnnotations() .ValidateOnStart();More in my Options Pattern guide.
32. Never Create a New HttpClient Per Request
Creating new HttpClient() for every call can run out of sockets under load. Register a typed client with AddHttpClient, and .NET reuses the connections for you.
builder.Services.AddHttpClient<GitHubClient>(c => c.BaseAddress = new Uri("https://api.github.com"));See HttpClient in .NET 10 for resilience and retries.
33. Add a Health Check Endpoint
Two lines let your load balancer ask if your app is ready for traffic.
builder.Services.AddHealthChecks();app.MapHealthChecks("/health");Add database checks later with Health Checks in ASP.NET Core.
34. Turn On Rate Limiting
The built-in rate limiter stops one client from slowing your API down for everyone else. Requests over the limit get a 429.
builder.Services.AddRateLimiter(o =>{ o.RejectionStatusCode = StatusCodes.Status429TooManyRequests; o.AddFixedWindowLimiter("fixed", w => { w.PermitLimit = 100; w.Window = TimeSpan.FromMinutes(1); });});app.UseRateLimiter();
app.MapGroup("/api/products").RequireRateLimiting("fixed");A named policy only applies to the endpoints or groups that ask for it with RequireRateLimiting, so don’t forget that last line.
Full guide: Rate Limiting in ASP.NET Core.
35. Use Built-In OpenAPI With Scalar
Since .NET 9, the Web API template uses built-in OpenAPI support instead of Swashbuckle. Add Scalar (the Scalar.AspNetCore package) for a clean UI to read the docs and test endpoints.
builder.Services.AddOpenApi();app.MapOpenApi();app.MapScalarApiReference();I explain why Swagger was dropped in ASP.NET Core Dropped Swagger.
How Do You Keep EF Core Queries Fast?
Most slow .NET APIs I look at are slow because of their database queries. These nine tips fix the common causes.
36. Use AsNoTracking for Read-Only Queries
EF Core tracks every entity it loads so it can save changes later. If you only return the data, AsNoTracking() skips that work.
var products = await db.Products.AsNoTracking().Where(p => p.IsActive).ToListAsync(ct);My benchmarks are in Tracking vs No-Tracking Queries in EF Core 10.
37. Select Only the Columns You Need
This is the one I end up fixing in almost every API I look at. The endpoint loads the whole entity with 20 columns, and then maps 3 of them to a DTO. Put the DTO inside the query with Select, and the database only sends back those 3 columns.
var products = await db.Products .Select(p => new ProductDto(p.Id, p.Name, p.Price)) .ToListAsync(ct);A projection is also read-only by nature, so you don’t need AsNoTracking() here.
38. Watch Out for N+1 Queries
N+1 happens when one query loads a list and then each item fires its own extra query, so 100 orders means 101 queries. Load related data up front with Include, or use a Select projection.
var orders = await db.Orders.Include(o => o.Customer).ToListAsync(ct);10 EF Core Performance Mistakes (and How to Fix Them) in .NET 10
N+1, missing projections, tracking and seven more mistakes with real fixes.
39. Use ExecuteUpdate and ExecuteDelete for Bulk Changes
These run one SQL statement, so you don’t load a thousand rows into memory to change one column.
await db.Products .Where(p => p.Stock == 0) .ExecuteUpdateAsync(s => s.SetProperty(p => p.IsActive, false), ct);I benchmarked the options in Bulk Operations in EF Core 10.
40. Use AnyAsync to Check if Something Exists
CountAsync() > 0 counts every matching row, while AnyAsync() stops at the first match, which is all you need to know that something exists.
41. Paginate Every List Endpoint
A table with ten rows today can have a million next year, so always return one page at a time.
var items = await db.Products.OrderBy(p => p.Id) .Skip((page - 1) * pageSize).Take(pageSize) .ToListAsync(ct);More patterns in Pagination, Sorting and Searching in ASP.NET Core.
42. Add Indexes on Columns You Filter By
If you often search orders by email, an index turns a full table scan into a quick lookup. EF Core indexes foreign keys for you, but other filter columns need their own.
modelBuilder.Entity<Order>().HasIndex(o => o.CustomerEmail);43. Soft Delete With a Named Query Filter
With soft delete, you mark rows with an IsDeleted column instead of removing them, and a query filter hides them from every query. EF Core 10 lets you name the filter, so an admin screen can switch off just that one.
modelBuilder.Entity<Product>().HasQueryFilter("SoftDelete", p => !p.IsDeleted);
var all = await db.Products.IgnoreQueryFilters(["SoftDelete"]).ToListAsync(ct);Full guide: Soft Deletes in EF Core 10.
44. Change the Schema Only Through Migrations
Never change a production table by hand. Migrations live in Git with your code, and an idempotent script is safe to run more than once.
dotnet ef migrations add AddOrderEmailIndexdotnet ef migrations script --idempotent -o migrate.sqlCompare the options in Running Migrations in EF Core 10.
How Do You Log, Test and Ship With Confidence?
45. Use Structured Logging
Use a message template with placeholders instead of string interpolation, so the value is saved as its own searchable field.
logger.LogInformation($"Order {orderId} created"); // just textlogger.LogInformation("Order {OrderId} created", orderId); // searchable OrderId fieldSerilog in ASP.NET Core .NET 10 - Structured Logging Done Right
Set up Serilog, enrich your logs and send them to Seq or the console.
46. Never Log Secrets or Personal Data
Logs get copied to many tools and kept for months. Never log passwords, tokens, card numbers or request bodies with personal data.
47. Log the SQL That EF Core Generates (in Development)
Most N+1 problems are obvious once you see fifty queries scroll past for one request.
builder.Services.AddDbContext<AppDbContext>(options =>{ options.UseNpgsql(connectionString); if (builder.Environment.IsDevelopment()) options.LogTo(Console.WriteLine, LogLevel.Information);});48. Write Integration Tests With WebApplicationFactory
WebApplicationFactory runs your real API in memory, so one test checks routing, validation and database code together.
public class ProductTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>>{ [Fact] public async Task GetProducts_ReturnsOk() { var response = await factory.CreateClient().GetAsync("/api/products"); response.EnsureSuccessStatusCode(); }}49. Use dotnet watch While You Code
Run dotnet watch, and your app reloads every time you save a file, so you stop restarting the debugger after every small change.
50. Build Containers Without a Dockerfile
The .NET SDK can build a container image for you, with no Dockerfile to maintain.
dotnet publish --os linux --arch x64 /t:PublishContainerStep-by-step guide: Containerize .NET 10 Apps Without a Dockerfile.
Which Tips Should You Apply First?
Here is how I would split the 50 tips by effort. Pick one from the first row and do it today.
| When | Tips |
|---|---|
| Today (under an hour) | #2 slnx, #6 NuGet audit, #8 user secrets, #28 ProblemDetails, #33 health checks, #35 OpenAPI + Scalar, #40 AnyAsync, #49 dotnet watch |
| This sprint | #1 upgrade to .NET 10, #3 Directory.Build.props, #4 Central Package Management, #29 global exception handler, #30 validation, #31 options with ValidateOnStart, #34 rate limiting, #47 SQL logging, #48 integration tests |
| Next time you touch that code | Everything else: the C# habits (#9-17), async fixes (#18-22), DI fixes (#23-24) and query fixes (#36-44) as you work in those files |
If I opened your project today, these are the three I would do first:
- Upgrade to .NET 10 (#1), because .NET 8 and .NET 9 no longer get security fixes.
- Add one global exception handler (#29), so every error is logged once and looks the same to your frontend.
- Put a
Selectin your slowest query (#37), because it is usually the biggest speed win for the least code.
Key Takeaways
- .NET 8 and .NET 9 reached end of support on November 10, 2026. .NET 10 is LTS and supported until November 2028, so upgrade first.
- In EF Core,
Selectprojections,AsNoTracking, pagination and avoiding N+1 queries fix most slow endpoints. - Every new API should start with ProblemDetails, a global exception handler, validation, health checks, rate limiting and OpenAPI.
- Build habits that cost nothing: pass the
CancellationToken, use structured logging and never block on async code.
FAQ
Should I upgrade from .NET 8 to .NET 10?
Yes. .NET 8 and .NET 9 both reached end of support on November 10, 2026, so they no longer get security fixes. .NET 10 is a Long Term Support release supported until November 14, 2028. For most apps, the upgrade means changing the target framework to net10.0 and updating Microsoft packages to their 10.x versions.
Is Swagger removed in .NET 10?
Swashbuckle was removed from the Web API template in .NET 9, and .NET 10 keeps the built-in OpenAPI support instead. You call AddOpenApi and MapOpenApi to generate the document, and you can add Scalar or another UI on top of it to read and test your endpoints.
What is the easiest way to make EF Core queries faster?
Use Select to return only the columns you need, add AsNoTracking to read-only queries, paginate every list endpoint, and watch for N+1 queries by logging the generated SQL in development. Adding indexes on columns you filter by also helps a lot on bigger tables.
Do I still need try-catch blocks in every endpoint?
No. Register one class that implements IExceptionHandler together with AddProblemDetails and UseExceptionHandler. Every unhandled exception then goes through one place, gets logged once, and returns a consistent ProblemDetails response to the client.
Why should I avoid .Result and .Wait() in ASP.NET Core?
They block a thread while the task finishes. Under load, many blocked threads make the whole API slow and can lead to thread pool starvation. Using await frees the thread while it waits, so the server can handle other requests in the meantime.
Which .NET 10 tip should I apply first?
Upgrade to .NET 10 first, because .NET 8 and .NET 9 no longer get security fixes after November 10, 2026. After that, add one global exception handler and put a Select projection in your slowest EF Core query. Quick wins like NuGet audit, user secrets, health checks and dotnet watch take less than an hour each.
Why does my build fail with hundreds of errors after turning on Nullable warnings as errors?
Every nullable warning that was already in the codebase now stops the build. On an older project, turn the setting on for new projects first, or fix the warnings one project at a time before you add it to Directory.Build.props for the whole solution.
Why does my ASP.NET Core rate limiter not block any requests?
A named policy such as a fixed window limiter only applies to endpoints that opt in. Add RequireRateLimiting with the policy name to your endpoints or route groups, and make sure app.UseRateLimiter is called after routing, otherwise no request is ever limited.
Summary
These 50 tips cover the whole life of a .NET 10 project, from setup and everyday C# to the API, EF Core, logging, testing and shipping.
Don’t apply all 50 at once. Pick one from the “today” row and try it in your project today. If you want to build a full .NET 10 Web API with these practices from scratch, my free .NET Web API Zero to Hero course walks you through it step by step.
Happy Coding :)
What's your take?
Push back, share a war story, or ask the obvious question someone else is wondering. I read every comment.