.Net 7 New Features

In this article, we will discuss .Net 7 new features with examples. The most recent version of Microsoft's well-known open-source framework for creating and executing applications .NET 7, was just published. There are several new features and enhancements included in .NET 7 that are intended to make it simpler for programmers to create reliable, scalable, and high-performance applications. It comes with a range of new features and improvements that enhance developer productivity, performance, and interoperability. In this post, we'll discuss some of the most notable .NET 7 features and provide usage examples.

Some of the top new key features in .Net 7 are listed below:


  •             API Controller (Parameter binding with DI in API controllers):


    • Source Generators:


    • Rate Limiter:


    • Minimal APIs


    • gRPC health checks:


    • Performance (Output caching middleware):


    • HTTP/3 support:


    • SignalR:


Let’s look at each of these key features in .Net 7.


API Controller (Parameter binding with DI in API controllers) :


Incoming HTTP request data is mapped to action method parameters by parameter binding, which enables programmers to process requests and replies logically and effectively. The handling of requests over HTTP is made simpler via parameter binding, which frees developers to concentrate on creating the logic for their API endpoints. The FromQuery, FromRoute, FromHeader, and FromBody forms of parameter binding are available in ASP.NET Core 7's minimal APIs.

Using ASP.NET Core 7, you may use dependency injection to bind arguments in your API controllers' action methods. Therefore, you no longer need to include the [FromServices] attribute in your method arguments if the type is configured as a service.

This is demonstrated in the following line of code.


[Route("[controller]")]

[ApiController]

public class MyController : ControllerBase

{

    public ActionResult Get(IDateTime dateTime) => Ok(dateTime.Now);

}



You can bind arguments without using the [FromServices] property if the type is set up as a service. Instead, you can bind parameters using dependency injection by implementing the following portion of code.


var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<IDateTime, SystemDateTime>();

var app = builder.Build();

app.MapGet("/",   (IDateTime dateTime) => dateTime.Now);

app.MapGet("/demo", ([FromServices] IDateTime dateTime) => dateTime.Now);

app.Run();




Source Generators:


Source generators are a new feature in .NET 7 that allows developers to generate source code at build time. This feature can be used to automatically generate boilerplate code or to provide custom implementations for interfaces. Source generators are implemented as .NET assemblies that are executed at build time, and they can be created using C# or any other .NET language.

One example of how source generators can be used is to automatically generate code that implements the builder pattern. The builder pattern is a design pattern that is used to create complex objects by using a simple step-by-step approach. By using a source generator, developers can automate the process of generating builder classes for their objects, which can save time and reduce errors.

Here's an example of how a source generator can be used to generate builder classes:


[AutoBuilder]

public class Person

{

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Age { get; set; }

}


// Generated builder class

public static class PersonBuilder

{

    public static Person Build(Action<Person> action)

    {

        var person = new Person();

        action(person);

        return person;

    }

}


In this example, the [AutoBuilder] attribute is used to indicate that a source generator should be used to generate a builder class for the Person class. The generated builder class provides a Build method that takes an action delegate that can be used to configure the properties of the Person object.



Rate Limiter:


Rate limiting is a common technique used in software development to restrict the number of requests or actions that can be performed within a specific time frame. The new rate-limiting middleware in .NET 7 allows developers to configure the maximum number of requests that can be made within a specific time window, as well as the duration of that time window.

A rate limiter is a tool that limits the number of requests that can be made to an API or service within a given time period. In .NET 7, a rate limiter has been added to the HttpClient class to simplify the implementation of rate limiting. Here's an example:


var handler = new RateLimitingHandler(TimeSpan.FromSeconds(1), 10);


var client = new HttpClient(handler);


In this example, a new RateLimitingHandler is created with a time span of 1 second and a limit of 10 requests per second. The HttpClient is then created with the RateLimitingHandler as its handler.

When using the HttpClient, any requests that exceed the rate limit will result in a 429 Too Many Requests response. You can read more about RateLimiting in .Net 7 by following the link :

Rate Limiter in .Net 7


Minimal APIs:


Filters give you the ability to run code throughout specific phases of the request processing pipeline. An action method is carried out either before or after a filter. Filters can be used to track web page visitors or verify the request parameters, Instead of coding code for the application's cross-cutting concerns, you can concentrate on the business logic of your application by employing filters.

With the help of an endpoint filter, you can intercept, alter, bypass, and combine universal problems like exception handling, authorization, and validation. With ASP.NET Core 7, we can create filters and attach them to API endpoints using the new IEndpointFilter interface. These filters have the potential to alter request or response objects or stop the processing of requests altogether. Both actions and route endpoints can call an endpoint filter.

The Microsoft.AspNetCore.Http namespace, as shown below, contains the definition of the IEndpointFilter interface.


public interface IEndpointFilter

{

    ValueTask<object?> InvokeAsync(

        EndpointFilterInvocationContext context,

        EndpointFilterDelegate next);

}


The chaining of various endpoint filters is demonstrated in the following code snippet.


app.MapGet("/", () =>

{

    return "Demonstrating multiple endpoint filters.";

})


.AddEndpointFilter(async (endpointFilterInvocationContext, next) =>

    {

        app.Logger.LogInformation("This is First filter.");

        var result = await next(endpointFilterInvocationContext);

        return result;

    })


.AddEndpointFilter(async (endpointFilterInvocationContext, next) =>

    {

        app.Logger.LogInformation("This is Second filter.");

        var result = await next(endpointFilterInvocationContext);

        return result;

    })


.AddEndpointFilter(async (endpointFilterInvocationContext, next) =>

    {

        app.Logger.LogInformation("This is Third Filter.");

        var result = await next(endpointFilterInvocationContext);

        return result;

    });



  • To execute cross-cutting code before or following a route handler, use endpoint filters.


  • From basic APIs, return highly typed results.


  • Utilize a common prefix to group endpoints in routes.



gRPC health checks:


The use of the .NET Health Checks middleware to report the condition of your application infrastructure components is supported by ASP.NET Core. Through the Grpc.AspNetCore.HealthChecks NuGet package, ASP.NET Core 7 introduces built-in support for gRPC service health monitoring. To implement health checks in your gRPC project, you can use this package to expose an endpoint. Keeping in mind that health checks are often used in conjunction with an external monitoring system, a load balancer, or a container orchestrator. Based on the service's health condition, the latter could automate a task like restarting it or rerouting traffic around it.

The gRPC client factory is set up to send Authorization metadata using the code below:



builder.
Services

    .AddGrpcClient<Greeter.GreeterClient>(o =>

    {

       o.Address = new Uri("https://localhost:5001");

    })

    .AddCallCredentials((context, metadata) =>

    {

       if (!string.IsNullOrEmpty(_token))

       {

          metadata.Add("Authorization", $"Bearer {_token}");

       }

       return Task.CompletedTask;

    });



Performance (Output caching middleware):


All ASP.NET Core apps, including Minimal API, MVC, Razor Pages, and Web API apps with controllers, are eligible to use output caching under ASP.NET Core 7. To add the middleware to the request processing pipeline, call the IApplicationBuilder.UseOutputCache extension method. To add the output caching middleware to the services collection, invoke the IServiceCollection.AddOutputCache extension method.

Then, you can use the code below to add a cache layer to an endpoint.


var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/", () => "Hello World!").CacheOutput();

app.Run();



  • Utilizing adaptive endpoint configuration and policies, reduce the volume of handled requests.


  • To better handle requests, configure caching for responses.



  • Accept content requests with compression.


  • built-in assistance for HTTP/3, the newest iteration of the protocol built on top of the QUIC multiplexed transport standard.



  • Instead of HTTP/2 connections, use WebSockets.


  • Over HTTP/3, create streams and datagrams with experimental WebTransport functionality.



HTTP/3 support:


HTTP/3 is the latest version of the HTTP protocol, which is used to transfer data over the Internet. HTTP/3 is supported in .NET 7, which was released in November 2021. .NET 7 includes a new implementation of the HttpClient class, which supports HTTP/3. .NET 7 includes support for HTTP/3, allowing developers to build applications that can take advantage of the latest improvements in network performance and security. HTTP/3 is designed to be faster and more reliable than previous versions of the protocol, making it ideal for applications that need to transfer large amounts of data quickly and efficiently.



SignalR:


Calling server methods is made possible by the SignalR Hubs API for connected clients. Both the client and the server define methods that are called from them, and vice versa. Real-time communication between clients and servers is made possible by SignalR, which handles all necessary tasks.

To register the services required by SignalR hubs, call AddSignalR in Program.cs:


var builder = WebApplication.CreateBuilder(args);


builder.Services.AddRazorPages();

builder.Services.AddSignalR();



To configure SignalR endpoints, call MapHub, also in Program.cs:


app.MapRazorPages();

app.MapHub<ChatHub>("/Chat");


app.Run();



The server now permits clients to ask for results. This requires the server to use ISingleClientProxy.InvokeAsync and the client to return a result from its .On handler. Strongly-typed hubs can also return values from interface methods.


public class ChatHub : Hub

{

    public async Task<string> WaitForMessage(string connectionId)

    {

        var message = await Clients.Client(connectionId).InvokeAsync<string>(

            "GetMessage");

        return message;

    }

}





Conclusion:


Overall, .NET 7 brings many exciting new features and improvements to the .NET platform, making it easier and more efficient for developers to create high-performance, modern applications. These are just a few of the many new features and improvements included in .NET 7. Developers should also note that .NET 7 has several performance improvements and bug fixes that can help make their applications faster and more reliable.

Hope you enjoyed reading this article and found it useful. Please share your thoughts and recommendations in the comment section below.


Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee