Are you ready for the latest enhancements and improvements in ASP.NET Core? Microsoft is gearing up to release Preview 5, which will introduce several exciting features that will make your development experience even smoother.
In this article, we’ll take a look at some of the upcoming features that you can expect in ASP.NET Core Preview 5.
From sleeker syntax to enhanced functionality, these additions will empower developers to build better web applications with ease.
So, let’s dive in and explore what’s in store in the latest preview release of ASP.NET Core!
Better Debugging Experience
Are you tired of wasting time navigating through nested properties while debugging your ASP.NET Core application? Well, say goodbye to those frustrating moments!
These attributes allow you to quickly access important data from types like HttpContext
, HttpRequest
, HttpResponse
, and ClaimsPrincipal
in the Visual Studio debugger. No more manual digging through nested properties – now you can easily visualize the key data you need without any hassle. Let’s dive deeper into this feature and see how it can make your debugging process a breeze.
And of course, as always, Microsoft offers us some sample images so we can see the differences between the versions of ASP.NET Core 7 and 8:
As you can see, the debugging experience in .NET 8 is much cleaner and more intuitive. With the help of debug customization attributes, you can easily access important data and understand the state of objects during your debugging sessions.
Not only does this enhancement save you time, but it also reduces the cognitive load when analyzing complex types. So next time you’re debugging an ASP.NET Core application, embrace the power of debug customization attributes and enjoy a smoother debugging experience.
IHttpSysRequestTimingFeature
Get ready to dive into the exciting world of server request timing with the introduction of the IHttpSysRequestTimingFeature in ASP.NET Core preview 5 of .NET 8! With IHttpSysRequestTimingFeature
we will have a higher level of detail in the timestamp data.
In previous versions it was common to use IHttpSysRequestInfoFeature
but with this improvement we will be able to have a more comfortable access to this data.
This means more precise control over tracking and analyzing how your server is handling incoming requests.
Let’s take a look at an example of how you can leverage this feature in your code:
// Retrieve IHttpSysRequestTimingFeature from the HttpContext
var timingFeature = context.Features.Get<IHttpSysRequestTimingFeature>();
// Use the timing information to measure request processing time
var start = timingFeature.StartTimestamp;
// ... Perform request processing ...
var end = timingFeature.EndTimestamp;
var duration = end - start;
// Output the request processing time
Console.WriteLine($"Request processing time: {duration.TotalMilliseconds} ms");
With the IHttpSysRequestTimingFeature, you can now gain valuable insights into the duration it takes for requests to be processed by your server. This can help you optimize your application’s performance, identify any bottlenecks, and ensure a seamless user experience. So, why wait? Dive into the world of request timing and take your server performance to new heights!
Let’s delve into the features of the IHttpSysRequestTimingFeature interface:
namespace Microsoft.AspNetCore.Server.HttpSys
{
public interface IHttpSysRequestTimingFeature
{
ReadOnlySpan<long> Timestamps { get; }
bool TryGetTimestamp(HttpSysRequestTimingType timestampType, out long timestamp);
bool TryGetElapsedTime(HttpSysRequestTimingType startingTimestampType, HttpSysRequestTimingType endingTimestampType, out TimeSpan elapsed);
}
}
The Timestamps property grants developers access to a plethora of HTTP.sys timing timestamps. These timestamps are acquired using the QueryPerformanceCounter function, and you can determine the frequency of the timestamps using the QueryPerformanceFrequency function.
To retrieve the timestamp for a specific timing type, the TryGetTimestamp method comes to the rescue. Additionally, the TryGetElapsedTime method allows you to calculate the elapsed time between two specified timings.
Now, you may be thinking, “What’s in it for me as a developer?” Well, let’s take a look at the benefits you can enjoy with IHttpSysRequestTimingFeature:
- Better insight: Improved view of the different stages of application processing. You can gain a more in-depth understanding of how your application works internally, which can prove invaluable in optimizing its performance.
- Powerful diagnostics: With precise timestamp data at your disposal, you can leverage powerful performance diagnostics capabilities. By identifying bottlenecks and optimizing your application accordingly, you can ensure it runs at its best.
- Greater control: The improved access to HTTP.sys request timing data gives you more control over your application. You can closely monitor and optimize request processing times at various stages, resulting in improved performance and efficiency.
If we closely monitor request processing times and identifying areas for improvement, you can optimize resource allocation and deliver lightning-fast and highly efficient applications. So, embrace the power of IHttpSysRequestTimingFeature and unleash the full potential of your ASP.NET Core applications!
SNI Hostname in ITlsHandshakeFeature
Have you ever needed to host multiple virtual hosts in your ASP.NET Core application? Well, in such situations, it’s essential to ensure that the correct security certificate is presented during the TLS handshake process.
In the latest preview 5 of .NET 8, ASP.NET Core brings a fantastic enhancement by exposing the SNI hostname through the ITlsHandshakeFeature
interface. You may ask yourself, what is the use of this? Well dear dev, with this SNI extension you will be able to have easy access to a client’s specific host name.
Now let me show you how you can leverage this feature to enhance your application’s security. Check out the code snippet below.
Here’s a sample code snippet that showcases this feature:
/// <summary>
/// Gets the host name from the "server_name" (SNI) extension of the client hello if present.
/// See <see href="https://www.rfc-editor.org/rfc/rfc6066#section-3">RFC 6066</see>.
/// </summary>
// Accessing SNI hostname using ITlsHandshakeFeature
string? HostName => null;
By capturing the SNI hostname, you unlock a range of possibilities for your application. Let’s take a look at some of the benefits and use cases:
- Diagnostics: The exposed SNI hostname allows you to gather additional insights during debugging sessions, enabling you to better understand the connections made to your application.
- Rate limiting: With the SNI hostname information, you can implement rate limiting strategies specific to each virtual host or domain, providing granular control over your application’s resources.
- Routing: Leveraging the SNI hostname, you can route incoming requests to the appropriate handlers or controllers based on the virtual host or domain, ensuring seamless request processing.
- Billing: If your application charges based on different virtual hosts or domains, the SNI hostname can be used to track usage and generate accurate billing records.
Being able to analyze and troubleshoot TLS connections with the exposed SNI hostname significantly improves your debugging capabilities.
So, embrace the power of the SNI hostname in the ITlsHandshakeFeature, and take your ASP.NET Core applications to the next level of TLS connection analysis and troubleshooting.a
Servers & Middleware: IExceptionHandler
Exception handling is an essential aspect of building robust ASP.NET Core applications. And with the introduction of the IExceptionHandler
interface in ASP.NET Core preview 5 of .NET 8, handling exceptions has become even more powerful.
The IExceptionHandler
interface allows developers to catch and handle exceptions that occur during request processing. By implementing this interface, developers can define a callback that will be invoked when an exception is encountered. This callback can then be used to handle known exceptions and display appropriate error pages to the user.
This approach to exception handling helps to keep the implementation details hidden and provides a more user-friendly experience. Instead of exposing technical details of the exception, developers can present custom error messages or redirect users to specific error pages.
To register an IExceptionHandler
you can simply use the IServiceCollection.AddExceptionHandler<T>
method. This method allows you to add multiple exception handlers, which will be executed in the order they are registered. It’s worth noting that if an exception handler successfully handles a request, it can return a boolean value of true
, indicating that further processing should be halted.
Let’s take a closer look at the IExceptionHandler
interface:
public interface IExceptionHandler
{
ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken);
}
The TryHandleAsync
method in the IExceptionHandler
interface takes three parameters: HttpContext
, Exception
, and CancellationToken
. It returns a ValueTask<bool>
, indicating whether the exception handling was successful or not.
SignalR Improvements
Are you tired of your SignalR clients experiencing downtime when they encounter temporary network disruptions? Well, with the new seamless reconnect feature introduced in ASP.NET Core preview 5 of .NET 8, those days are about to be behind you. This exciting feature aims to minimize the perceived downtime for clients that face temporary network interruptions, such as switching network connections or driving through tunnels.
But how does this seamless reconnect feature work its magic? It accomplishes its goal by implementing a buffering mechanism on both the server and client sides. This buffering mechanism allows them to temporarily store data and acknowledge messages sent by each party involved. Furthermore, it has the intelligence to recognize when a connection is restored and replay any messages that were sent during the downtime.
It’s important to note that since this feature is still in development, there is currently no configuration available. Additionally, the support for seamless reconnects is currently limited to .NET clients using WebSockets.
Here you can see a Microsoft example:
var hubConnection = new HubConnectionBuilder()
.WithUrl("<hub url>",
options =>
{
options.UseAcks = true;
})
.Build();
By setting the UseAcks
option to true
, you’re opting in to the seamless reconnect feature. This allows your client to leverage the buffering capabilities and message replay functionality, effectively minimizing the impact of temporary network disruptions on your application.
Although seamless reconnects are still in the early stages of development, they have the potential to greatly enhance the user experience by reducing any interruptions caused by temporary network issues. Say goodbye to frustrating downtime and embrace the seamless reconnect feature in SignalR!
New Blazor Web App project template
Get ready to embark on an exciting journey into the world of building web user interfaces with Blazor components! Its main benefits are that it will facilitate the creation of web apps in Blazor and will improve compatibility with user interfaces that are rendered. This gives you the flexibility to choose the hosting model that best suits your specific requirements and preferences.
With the Blazor Web App template, you’ll have access to a host of innovative features that come bundled with .NET 8. Although not all features are available in this preview version, you can start experimenting with the available ones and eagerly anticipate the upcoming additions.
Using the command:
dotnet new blazor -o BlazorWebApp
Or simply search it in the project templates:
Blazor Server interactivity
Are you ready to take your Blazor Server applications to the next level of interactivity? With the release of ASP.NET Core Preview 5, we now have a powerful new feature that allows us to enable interactivity for individual components using the Blazor Server rendering mode. This means that we can create dynamic and interactive web applications using C# on the server side.
To enable interactivity for a specific component, all we need to do is use the AddServerComponents
extension method provided by the Blazor Server services. And to mark components for server-side rendering, we can use the new [RenderModeServer]
attribute.
Let’s see how this works in practice. Suppose we want to create a Counter
component that increments a value when a button is clicked. We can start by creating a new page called Counter.razor
with the following code:
@page "/counter"
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
Next, we need to update the navigation menu NavMenu.razor
to include a link to the Counter
page. By simply adding the following code snippet, we enable users to navigate to the Counter
page:
<div class="nav-item px-3">
<NavLink class="nav-link" href="counter">
<span class="oi oi-plus" aria-hidden="true"></span> Counter
</NavLink>
</div>
But wait, there’s more! To enable interactivity for the Counter
component using Blazor Server, we need to make some updates in the Program.cs
file and the Counter.razor
file.
To add these services:
builder.Services.AddRazorComponents()
.AddServerComponents();
And in the Counter.razor
file, add [RenderModeServer]
:
@attribute [RenderModeServer]
And there you have it! Voilà! Now, when we navigate to the counter page, the magic begins. Brace yourself for an interactive experience like no other.
The onclick event joyfully dances into action, artfully incrementing the count with a single bound. Prepare to witness the true power of interactivity!
To kickstart your journey with an interactive Counter
component in a new Blazor Web App, you can use the following command:
dotnet new blazor --use-server -o BlazorWebApp
While the support for interactive WebAssembly is not fully implemented yet, rest assured that future updates will bring improvements and enhancements in managing the lifecycle of circuits.
Generic Attributes Improvements
With the introduction of support for generic attributes, you can now enjoy a simplified syntax when annotating elements in your code.
In previous versions of ASP.NET Core, certain attributes required the use of typeof(T)
to specify the desired type. However, with the support for generic attributes, you can now directly use the corresponding generic attribute and pass the type as a generic argument. Let’s take a look at an example using the ProducesResponseType
attribute:
[ApiController]
[Route("api/[controller]")]
public class TodosController : Controller
{
[HttpGet("/")]
[ProducesResponseType<Todo>(StatusCodes.Status200OK)]
public Todo Get() => new Todo(1, "Write a sample", DateTime.Now, false);
}
In the above code snippet, the ProducesResponseType<T>
attribute is used to specify the response type of the Get
action, eliminating the need for typeof(Todo)
.
Now the support extends to other attributes as well. This means you can take advantage of a cleaner and more expressive syntax when using attributes like [Produces<T>]
, [MiddlewareFilter<T>]
, [ModelBinder<T>]
, [ModelMetadataType<T>]
, [ServiceFilter<T>]
, and [TypeFilter<T>]
in your code.
Overall, the support for generic attributes in ASP.NET Core Preview 5 simplifies your code and improves readability by providing a cleaner syntax for annotating elements with attribute-based functionality. So why not make your code shine with cleaner and more concise annotations using generic attributes in ASP.NET Core?
Simplifying Code with AsParameters
& Automatic Metadata Generation (AOT)
Are you ready to level up your ASP.NET Core development? In ASP.NET Core Preview 5, exciting features have been introduced to simplify your code and streamline your development process. These enhancements build upon the previous introduction of compile-time code generation for minimal APIs in .NET 8 Preview 3, with a specific focus on supporting Native AOT scenarios.
But what does this mean for you?
Well, AsParameters
attribute have the ability to enhance the way parameters are bound in your APIs. By simply decorating parameters with this attribute, you will witness the magic unfold as the generated code accurately binds the parameters according to their specified attributes.
The automatic metadata generation feature makes it much easier to work with JSON payloads. The endpoint metadata is automatically inferred, allowing you to easily indicate the input and output types for your API endpoints.
Let’s take a closer look with a Microsoft example:
var app = WebApplication.Create();
app.MapPost("/todos", ([AsParameters] CreateTodoArgs payload) =>
{
if (payload.TodoToCreate is not null)
{
return payload.TodoToCreate;
}
return new Todo(0, "New todo", DateTime.Now, false);
});
app.Run();
record CreateTodoArgs(int ProjectId, Todo? TodoToCreate);
record Todo(int Id, string Name, DateTime CreatedAt, bool IsCompleted);
Here we can see that the AsParameters
attribute is applied to the CreateTodoArgs
parameter.
It streamlines and enhances efficiency by minimizing the need for manual configuration. As a result, your code becomes cleaner and more concise, allowing you to focus on developing the core functionalities of your application.
So, get ready to experience the benefits of the AsParameters
attribute and automatic metadata generation in your ASP.NET Core applications. Say goodbye to manual configuration and embrace a more streamlined and efficient development workflow. Your code will thank you!
From the support for generic attributes to the improvements in compile-time generated minimal APIs, these updates aim to streamline your workflow and make building web applications more efficient.
Microsoft’s dedication to improving ASP.NET Core shines through in these enhancements, offering developers more flexibility and power.
So, get ready to level up your ASP.NET Core skills with the upcoming Preview 5 release. Stay tuned for more exciting updates on the horizon as ASP.NET Core continues to evolve and empower developers worldwide.