| NET-Core-Native-AOT :👈 | 👉:Distributed Transaction-QA |
ASP.NET Core .NET 10 New Features: Complete Developer Guide |
ASP.NET Core .NET 10 New Features: Complete Developer Guide
1. Introduction to ASP.NET Core 10
ASP.NET Core 10 is the web development framework included with .NET 10. It is designed for building modern web applications, REST APIs, microservices, real-time applications, and cloud-native services.
.NET 10 is an LTS (Long-Term Support) release. It includes improvements to Minimal APIs, validation, OpenAPI, JSON processing, Blazor, SignalR, memory management, and application performance.
What can we build with ASP.NET Core 10?
- RESTful Web APIs
- Microservices and distributed applications
- Enterprise web applications
- Real-time applications using SignalR
- Blazor applications
- Cloud-native applications
- Native AOT applications
- Applications deployed using Docker and Kubernetes
2. Major New Features in .NET 10
| Feature | What changed? | Benefit |
|---|---|---|
| Minimal API Validation | Built-in request validation support | Less manual validation code |
| Server-Sent Events | Built-in SSE result support | Easy server-to-client streaming |
| JSON Patch | New System.Text.Json-based implementation | Modern JSON processing |
| OpenAPI | Improved document generation and metadata | Better API documentation |
| Native AOT Template | OpenAPI support included by default | Improved AOT project experience |
| Memory Pool Eviction | Unused memory blocks can be released automatically | Reduced memory usage during idle periods |
| JSON Deserialization | PipeReader-based JSON processing support | More efficient request processing |
| Blazor | Static asset fingerprinting and reconnection UI improvements | Improved deployment and user experience |
| Testing | Improved support for top-level statements | Simpler integration testing setup |
3. Minimal API Validation
What is Minimal API validation?
In earlier ASP.NET Core versions, developers commonly used manual validation, endpoint filters, or third-party validation libraries to validate incoming API requests.
ASP.NET Core 10 introduces built-in validation support for Minimal APIs through the AddValidation() extension method.
It supports validation using Data Annotations and IValidatableObject.
Enable validation
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidation();
var app = builder.Build();
app.MapPost("/products", (Product product) =>
{
return TypedResults.Ok(product);
});
app.Run();
public record Product(
[Required]
string Name,
[Range(1, 1000)]
int Quantity,
[Range(1, 100000)]
decimal Price
);
How does it work?
Example valid request
POST /products
{
"name": "Laptop",
"quantity": 5,
"price": 55000
}
The request passes validation if all defined rules are satisfied.
Example invalid request
{
"name": "",
"quantity": 0,
"price": 55000
}
The request fails because the name is required and quantity must be between 1 and 1000. ASP.NET Core returns HTTP 400 Bad Request with validation details.
Important points
- Call builder.Services.AddValidation() to enable built-in Minimal API validation.
- Validation supports query parameters, headers, and request body models.
- Validation attributes can be applied to classes and records.
- IValidatableObject can be used for custom object-level validation.
- Validation can be disabled for an endpoint using DisableValidation().
- Validation does not automatically reject every unmapped JSON property. Configure JSON unmapped-member handling separately when required.
- The validation source generator discovers types in the assembly where AddValidation() is called. Take this into account when endpoints are defined in separate assemblies.
4. Server-Sent Events (SSE)
What are Server-Sent Events?
Server-Sent Events allow a server to continuously send updates to a client over a single HTTP connection.
Unlike normal HTTP requests, where the client usually sends a request and receives one response, SSE allows the server to keep sending events to the client.
Example use cases
- Live order status updates
- Dashboard notifications
- Live monitoring data
- Background job progress
- Stock or weather information updates
- Application status notifications
Traditional HTTP vs SSE
Implement SSE in ASP.NET Core 10
using System.Runtime.CompilerServices;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/events", (CancellationToken cancellationToken) =>
{
async IAsyncEnumerable<SseItem<string>> GetEvents(
[EnumeratorCancellation]
CancellationToken cancellationToken)
{
var count = 1;
while (!cancellationToken.IsCancellationRequested)
{
yield return new SseItem<string>(
$"Notification {count++}",
eventType: "notification");
await Task.Delay(2000, cancellationToken);
}
}
return TypedResults.ServerSentEvents(
GetEvents(cancellationToken));
});
app.Run();
How it works
- The client connects to the /events endpoint.
- The server starts producing events.
- Each event is sent to the client.
- The connection remains open while events are being produced.
- The client can receive new updates without repeatedly requesting them.
SSE vs SignalR vs WebSockets
| Technology | Communication | Best use case |
|---|---|---|
| SSE | Server to client | Notifications and live feeds |
| SignalR | Two-way communication | Chat and real-time applications |
| WebSockets | Two-way communication | Low-latency interactive communication |
Important: SSE is one-way communication from server to client. Use SignalR or WebSockets when the application needs two-way real-time communication.
5. New JSON Patch Implementation
What is JSON Patch?
JSON Patch is a standard format for describing changes to a JSON document. It is defined by RFC 6902.
Instead of sending an entire object to update a resource, a client can send only the changes that need to be applied.
Example without JSON Patch
Suppose a product contains the following properties:
{
"id": 101,
"name": "Laptop",
"price": 55000,
"quantity": 10
}
If the client wants to change only the price, a traditional PUT request might send the entire object.
Example JSON Patch document
[
{
"op": "replace",
"path": "/price",
"value": 52000
}
]
This operation changes only the price property.
JSON Patch operations
| Operation | Purpose |
|---|---|
| add | Add a property or array element |
| remove | Remove a property or array element |
| replace | Replace an existing value |
| move | Move a value from one location to another |
| copy | Copy a value from another location |
| test | Check whether a value matches an expected value |
What changed in .NET 10?
ASP.NET Core introduces a new JSON Patch implementation based on System.Text.Json. Earlier implementations commonly relied on Newtonsoft.Json.
The new implementation follows modern System.Text.Json serialization practices and is designed to improve performance and reduce memory usage.
JSON Patch is powerful, but it must be used carefully. Validate allowed paths and operations, authorize updates, and avoid allowing clients to modify sensitive properties such as roles, account balances, or ownership fields.
6. OpenAPI Improvements
What is OpenAPI?
OpenAPI is a standard for describing HTTP APIs. It describes endpoints, request parameters, request bodies, response types, and authentication requirements.
Tools such as Swagger UI can use an OpenAPI document to display API documentation and help developers test endpoints.
Important .NET 10 improvements
- Improved XML documentation support.
- Better handling of complex types.
- Improved JSON schema reference resolution.
- Better support for schema transformers.
- Improved metadata for form parameters and enum types.
- Support for IOpenApiDocumentProvider through dependency injection.
- OpenAPI support included by default in the Native AOT Web API template.
Enable XML documentation
Add the following property to your project file:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
Example API with XML documentation
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
var app = builder.Build();
app.MapOpenApi();
app.MapGet("/products", GetProducts);
app.Run();
/// <summary>
/// Gets all available products.
/// </summary>
/// <returns>A collection of products.</returns>
static IEnumerable<string> GetProducts()
{
return new[] { "Laptop", "Keyboard", "Mouse" };
}
XML comments can provide useful descriptions in generated API documentation. For Minimal API handlers, place the XML comments on a named method rather than directly on a lambda expression.
7. Native AOT Improvements
What is Native AOT?
Native AOT stands for Native Ahead-of-Time compilation. It compiles application code into native machine code during publishing rather than relying on runtime JIT compilation.
Traditional .NET execution
Native AOT Execution
Create a Native AOT API project
dotnet new webapiaot -n NativeAotApi
cd NativeAotApi
dotnet run
Enable Native AOT in the project file
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<PublishAot>true</PublishAot>
</PropertyGroup>
Publish the application
dotnet publish -c Release -r linux-x64
Important Native AOT considerations
- Native AOT produces platform-specific executables.
- Reflection-heavy libraries may need additional configuration.
- Some dynamic code-generation techniques are not supported.
- Trimming can remove code that is not recognized as required.
- Use source-generated JSON serialization where appropriate.
- Check compatibility of third-party libraries and database providers.
- Measure real application performance before choosing AOT.
8. Memory Pool Improvements
What is a memory pool?
A memory pool is a mechanism that reuses allocated memory blocks instead of repeatedly allocating and releasing memory.
ASP.NET Core servers such as Kestrel use memory pools to improve efficiency when processing HTTP requests and responses.
What is new in .NET 10?
Memory pools used by Kestrel, IIS, and HTTP.sys can now automatically evict unused memory blocks when the application is idle or under lighter load.
How it works
Benefits
- Reduced memory usage during idle periods.
- Better memory management under changing workloads.
- Less unnecessary memory retention.
- New metrics available under Microsoft.AspNetCore.MemoryPool.
This behavior is automatic for the built-in memory pools; applications do not need to enable a special setting.
9. JSON Processing Improvements
PipeReader-based JSON deserialization
ASP.NET Core 10 improves JSON request processing by using System.Text.Json PipeReader support in MVC, Minimal APIs, and HttpRequestJsonExtensions.ReadFromJsonAsync.
PipeReader provides an efficient way to read data from a sequence of buffers. It is useful when processing network data and large or streamed inputs.
Conceptual flow
Important developer consideration
Most applications benefit without changing their code. However, custom JsonConverter implementations must correctly handle Utf8JsonReader.HasValueSequence. A converter that assumes all JSON data is available through ValueSpan may fail when the reader uses a sequence.
10. Blazor Improvements
10.1 Blazor script as a static web asset
In .NET 10, Blazor scripts such as blazor.web.js and blazor.server.js are served as static web assets instead of embedded resources in the ASP.NET Core shared framework.
The framework provides automatic compression and fingerprinting for these assets.
Benefits
- Improved static asset handling.
- Automatic asset fingerprinting.
- Automatic compression.
- Better integration with static web asset deployment.
10.2 Improved reconnection UI
The Blazor Web App template includes a ReconnectModal component to provide better control over the user interface when a client loses its WebSocket connection.
The updated reconnection experience includes:
- Different reconnection states.
- A retrying state.
- The components-reconnect-state-changed event.
- Better control over the reconnection UI.
- Improved compatibility with stricter Content Security Policy settings.
10.3 Persistent component state during enhanced navigation
Blazor supports handling persistent component state during enhanced navigation. Components can opt into receiving updates during enhanced navigation by using AllowUpdates = true on the PersistentState attribute.
[PersistentState(AllowUpdates = true)]
public WeatherForecast[]? Forecasts { get; set; }
This is useful for data that is relatively stable and expensive to retrieve.
11. Testing Improvements
Testing top-level statements
Earlier versions commonly required developers to add a public partial Program declaration manually when testing applications that used top-level statements.
In .NET 10, a source generator can generate the public partial Program declaration when needed. An analyzer can also detect an explicit declaration and suggest removing it.
Why is this useful?
- Less test setup code.
- Simpler WebApplicationFactory integration testing.
- Cleaner Program.cs files.
- Better support for modern ASP.NET Core templates.
12. Creating a Basic ASP.NET Core 10 Web API
Step 1: Check the installed SDK
dotnet --version
dotnet --list-sdks
Step 2: Create a Web API project
dotnet new webapi -n ProductApi
cd ProductApi
Step 3: Add validation and OpenAPI services
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidation();
builder.Services.AddOpenApi();
var app = builder.Build();
app.MapOpenApi();
app.MapGet("/", () => "ASP.NET Core 10 API is running!");
app.Run();
Step 4: Create a product model
using System.ComponentModel.DataAnnotations;
public record Product(
int Id,
[Required]
string Name,
[Range(1, 100000)]
decimal Price
);
Step 5: Add API endpoints
var products = new List<Product>
{
new(1, "Laptop", 55000),
new(2, "Keyboard", 1500)
};
app.MapGet("/products", () =>
{
return TypedResults.Ok(products);
});
app.MapGet("/products/{id:int}", (int id) =>
{
var product = products.FirstOrDefault(p => p.Id == id);
return product is not null
? TypedResults.Ok(product)
: TypedResults.NotFound();
});
app.MapPost("/products", (Product product) =>
{
products.Add(product);
return TypedResults.Created(
$"/products/{product.Id}",
product);
});
For a real application, use a database instead of an in-memory list. The list is only for demonstrating endpoint structure.
13. Recommended ASP.NET Core 10 Project Structure
ProductApi/
|
+-- Controllers/
| +-- ProductsController.cs
|
+-- Models/
| +-- Product.cs
|
+-- DTOs/
| +-- CreateProductRequest.cs
| +-- ProductResponse.cs
|
+-- Services/
| +-- IProductService.cs
| +-- ProductService.cs
|
+-- Repositories/
| +-- IProductRepository.cs
| +-- ProductRepository.cs
|
+-- Data/
| +-- ApplicationDbContext.cs
|
+-- Middleware/
| +-- ExceptionHandlingMiddleware.cs
|
+-- Validators/
| +-- ProductValidator.cs
|
+-- Program.cs
+-- appsettings.json
+-- ProductApi.csproj
14. ASP.NET Core 10 Best Practices
Performance
- Use asynchronous methods for database and network operations.
- Use efficient database queries and appropriate indexes.
- Use caching for frequently accessed data when appropriate.
- Use pagination for large collections.
- Avoid unnecessary object allocations.
- Measure performance using realistic workloads.
- Use response compression when appropriate.
Security
- Use HTTPS for production applications.
- Use authentication and authorization policies.
- Validate all incoming requests.
- Use parameterized SQL queries or EF Core.
- Store secrets outside source code.
- Apply rate limiting to sensitive endpoints.
- Configure CORS with specific trusted origins.
- Use secure cookie settings when using cookie authentication.
- Keep NuGet dependencies updated.
Architecture
- Separate controllers or endpoints from business logic.
- Use dependency injection.
- Use DTOs instead of exposing database entities directly.
- Centralize exception handling.
- Use structured logging.
- Use health checks for production services.
- Use OpenAPI to document APIs.
- Use background services for suitable background processing tasks.
15. Migration from .NET 8 to .NET 10
When upgrading an ASP.NET Core application from .NET 8 to .NET 10, follow a controlled migration process.
Step 1: Install the .NET 10 SDK
Install the appropriate .NET 10 SDK and verify it using:
dotnet --list-sdks
Step 2: Update the target framework
Change the project file:
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
Step 3: Update NuGet packages
Review Microsoft.Extensions packages, Entity Framework Core packages, authentication packages, and third-party dependencies for .NET 10 compatibility.
Step 4: Review breaking changes
- Review ASP.NET Core 10 breaking changes.
- Check custom JSON converters.
- Check authentication and authorization behavior.
- Check middleware and hosting configuration.
- Review third-party library compatibility.
Step 5: Build and test
dotnet restore
dotnet build
dotnet test
Step 6: Publish and deploy
dotnet publish -c Release
Test the application in a staging environment before deploying it to production.
16. Common Mistakes to Avoid
| Mistake | Better approach |
|---|---|
| Assuming AddValidation rejects unknown JSON properties | Configure unmapped-member handling separately if needed. |
| Using SSE for two-way communication | Use SignalR or WebSockets. |
| Applying JSON Patch without authorization checks | Restrict allowed paths and operations. |
| Assuming Native AOT supports all reflection-based libraries | Verify AOT compatibility and test publishing. |
| Ignoring custom JsonConverter sequence handling | Handle both ValueSpan and ValueSequence. |
| Using an in-memory collection in production | Use a persistent database. |
| Upgrading without testing dependencies | Test all packages and integrations. |
17. Final Takeaways
- ASP.NET Core 10 improves Minimal API validation.
- SSE provides a built-in way to stream server events to clients.
- JSON Patch now has a System.Text.Json-based implementation.
- OpenAPI generation includes improved metadata and documentation support.
- Native AOT project templates have improved OpenAPI support.
- Memory pools can release unused memory automatically.
- JSON processing benefits from PipeReader support.
- Blazor receives static asset and reconnection improvements.
- Testing applications with top-level statements is simpler.
18. Official Microsoft Documentation
| NET-Core-Native-AOT :👈 | 👉:Distributed Transaction-QA |