ASP.NET Core and Blazor in .NET 9: A Deep Dive with Code Examples
1. Blazor Web Apps: Full Stack Flexibility
.NET 8 introduced the Blazor Web App model, allowing seamless full-stack web UI development with a single project. .NET 9 further refines this model by addressing crucial developer concerns.
- Detecting the Current Render Mode:
In .NET 9, developers can leverage the RenderMode directive to specify a specific render mode (InteractiveServer, InteractiveWebAssembly, or InteractiveAuto) and access the current render mode using RenderInfo. This enables developers to customize component behavior based on the context.
@page "/counter"
@rendermode InteractiveAuto
<h3>Render mode: @RenderInfo.Name</h3>
@if (RenderInfo.IsInteractive)
{
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
}
else
{
<p>Wait for it...</p>
}
@code {
// ...
}
- Static Server Rendering from an Interactive Context:
While using interactive mode, developers can force specific components or pages to render statically from the server using the RenderMode directive. This is useful for scenarios like authentication pages that require server-side logic to set cookies.
@page "/login"
@rendermode InteractiveServer
// Rest of the page content
- Microsoft Entra Authentication Docs & Sample:
.NET 9 provides comprehensive documentation and samples for implementing Microsoft Entra authentication in Blazor Web Apps, simplifying the process for developers.
2. Blazor Server Enhancements:
- Improved Reconnection Logic:
In .NET 9, the reconnection UI for Blazor Server apps has been improved to provide a more user-friendly experience when the connection drops. The reconnection attempts are faster and more efficient, minimizing disruptions for the user.
- WebSocket Message Compression:
This improvement reduces the payload size transmitted between the server and client, enhancing UI responsiveness and performance for Blazor Server applications.
3. Static Web Asset Optimization:
.NET 9 optimizes the handling of static web assets like JavaScript, CSS, and images for faster page loading and improved caching.
- Precompression: .NET 9 precompresses all uncompressed static assets at build time. This saves bandwidth and reduces download times, making your application load faster.
- Fingerprinting: Unique hashes are added to static asset file names on publish, ensuring that when you update files, clients receive the latest versions and avoid cached, outdated assets.
- Caching: The new MapStaticAssets API in .NET 9 provides better control and efficiency for serving static assets, addressing potential caching conflicts that could arise with the older UseStaticFiles middleware.
4. Improved Developer Experience:
- Constructor Injection for Blazor Components:
.NET 9 simplifies dependency injection into Blazor components by enabling constructor injection. This eliminates the need for the [Inject] attribute and allows for optional service injection, improving code readability and robustness.
- Improved Hot Reload: .NET 9 enhances the Hot Reload experience, making it faster, more reliable, and capable of handling more complex code changes. This significantly speeds up the development workflow for Blazor developers.
- Improved Blazor WebAssembly Debugging: The new .NET 9 Mono debugger provides a more robust and accurate debugging experience for Blazor WebAssembly applications. It offers better handling of data types, a cleaner call stack, and improved expression parsing.
- Blazor Hybrid + Web Project Template: This new template allows developers to create a .NET MAUI Blazor Hybrid application alongside a corresponding Blazor Web App, sharing UI components between both platforms. This facilitates cross-platform development with a unified codebase.
5. Built-in Open API Support:
.NET 9 introduces built-in Open API support in ASP.NET Core, simplifying API development and documentation.
- Document Generation: ASP.NET Core automatically generates Open API documentation for minimal APIs and controller-based APIs at both runtime and build time.
- Customization: Developers can customize the generated documentation using document transformers, providing flexibility and control over the output.
- Testing: Support for ad-hoc testing UIs using third-party packages like Swashbuckle.AspNetCore.SwaggerUI simplifies API testing and validation.
- Native AOT-compatible: The new Open API support is compatible with Native AOT compilation, offering performance benefits for scenarios where size and startup time are critical.
6. HybridCache: Simplifying Distributed Caching
HybridCache is a new API that simplifies and enhances distributed caching in .NET 9.
- Simpler API: The GetOrCreateAsync method simplifies common caching scenarios with a single line of code, abstracting away the complexities of byte array handling and cache miss handling.
- Stampede Protection: Prevents multiple concurrent requests from hitting the data source when a cache entry is missing, improving efficiency and performance.
- Multi-tier Caching: Supports a multi-tier approach, prioritizing in-memory caching and falling back to distributed caches like Redis when needed.
- Enhanced Features: Built-in serialization, tagging and invalidation, and an efficient low-allocation API for better performance.
Conclusion
With its emphasis on performance, developer experience, and solid fundamentals, ASP.NET Core in .NET 9 offers a wealth of improvements for building modern, robust, and efficient web applications. By incorporating these new features and utilizing the provided code examples, developers can unlock the full potential of the framework and enhance their development workflow.