A significant a part of Microsoft’s “cloud-first” .NET 7 launch in November, ASP.NET Core 7 brings highly effective new instruments to the online improvement framework to assist builders create trendy internet functions. Constructed on prime of the .NET Core runtime, ASP.NET Core 7 has all the pieces it’s essential construct cutting-edge internet consumer interfaces and sturdy back-end providers on Home windows, Linux, and macOS alike.
This text discusses the most important highlights in ASP.NET Core 7, and contains some code examples to get you began with the brand new options. To work with the code examples offered on this article, it’s best to have Visible Studio 2022 put in in your pc. For those who don’t have a duplicate, you possibly can obtain Visible Studio 2022 right here.
Now let’s dive into the most effective new options in ASP.NET Core 7.
Output caching middleware
ASP.NET Core 7 lets you use output caching in all ASP.NET Core apps: Minimal API, MVC, Razor Pages, and Internet API apps with controllers. So as to add the output caching middleware to the providers assortment, invoke the IServiceCollection.AddOutputCache extension technique. So as to add the middleware to the request processing pipeline, name the IApplicationBuilder.UseOutputCache extension technique.
Then, so as to add a caching layer to an endpoint, you should utilize the next code.
var builder = WebApplication.CreateBuilder(args); var app = builder.Construct(); app.MapGet("https://www.infoworld.com/", () => "Whats up World!").CacheOutput(); app.Run();
Charge-limiting middleware
Controlling the speed at which purchasers could make requests to endpoints is a vital safety measure that permits internet functions to beat back malicious assaults. You’ll be able to forestall denial-of-service assaults, for instance, by limiting the variety of requests coming from a single IP tackle in a given time period. The time period for this functionality is fee limiting.
The Microsoft.AspNetCore.RateLimiting middleware in ASP.NET Core 7 will help you implement fee limiting in your software. You’ll be able to configure rate-limiting insurance policies after which connect these insurance policies to the endpoints, thereby defending these endpoints from denial-of-service assaults. This middleware is especially helpful for public-facing internet functions which can be inclined to such assaults.
You should use the rate-limiting middleware with ASP.NET Core Internet API, ASP.NET Core MVC, and ASP.NET Core Minimal API apps. To get began utilizing this built-in middleware, add the Microsoft.AspNetCore.RateLimiting NuGet bundle to your mission by executing the next command on the Visible Studio command immediate.
dotnet add bundle Microsoft.AspNetCore.RateLimiting
Alternatively, you possibly can add this bundle to your mission by operating the next command within the NuGet bundle supervisor console or console window:
Set up-Bundle Microsoft.AspNetCore.RateLimiting
As soon as the rate-limiting middleware has been put in, embrace the code snippet given under to your Program.cs file so as to add fee limiting providers with the default configuration.
builder.Companies.AddRateLimiter(choices => { });
Request decompression middleware
ASP.NET Core 7 features a new request decompression middleware that permits endpoints to just accept requests which have compressed content material. This eliminates the necessity to write code explicitly to decompress requests with compressed content material. It really works by utilizing a Content material-Encoding HTTP header to determine and decompress compressed content material in HTTP requests.
In response to an HTTP request that matches the Content material-Encoding header worth, the middleware encapsulates the HttpRequest.Physique in an appropriate decompression stream utilizing the matching supplier. That is adopted by the removing of the Content material-Encoding header, which signifies that the request physique is now not compressed. Observe that the request decompression middleware ignores requests with no Content material-Encoding header.
The code snippet under exhibits how one can allow request decompression for the default Content material-Encoding varieties.
var builder = WebApplication.CreateBuilder(args); builder.Companies.AddRequestDecompression(); var app = builder.Construct(); app.UseRequestDecompression(); app.MapPost("https://www.infoworld.com/", (HttpRequest httpRequest) => Outcomes.Stream(httpRequest.Physique)); app.Run();
The default decompression suppliers are the Brotli, Deflate, and Gzip compression codecs. Their Content material-Encoding header values are br, deflate, and gzip, respectively.
Filters in minimal APIs
Filters allow you to execute code throughout sure phases within the request processing pipeline. A filter runs earlier than or after the execution of an motion technique. You’ll be able to make the most of filters to trace internet web page visits or validate the request parameters. By utilizing filters, you possibly can give attention to the enterprise logic of your software relatively than on writing code for the cross-cutting considerations in your software.
An endpoint filter allows you to intercept, modify, short-circuit, and mixture cross-cutting points comparable to authorization, validation, and exception dealing with. The brand new IEndpointFilter interface in ASP.NET Core 7 lets us design filters and join them to API endpoints. These filters might change request or response objects or short-circuit request processing. An endpoint filter will be invoked on actions and on route endpoints.
The IEndpointFilter interface is outlined within the Microsoft.AspNetCore.Http namespace as proven under.
public interface IEndpointFilter { ValueTask<object?> InvokeAsync( EndpointFilterInvocationContext context, EndpointFilterDelegate subsequent); }
The next code snippet illustrates how a number of endpoint filters will be chained collectively.
app.MapGet("https://www.infoworld.com/", () => { return "Demonstrating a number of endpoint filters."; }) .AddEndpointFilter(async (endpointFilterInvocationContext, subsequent) => { app.Logger.LogInformation("That is the first filter."); var outcome = await subsequent(endpointFilterInvocationContext); return outcome; }) .AddEndpointFilter(async (endpointFilterInvocationContext, subsequent) => { app.Logger.LogInformation("That is the 2nd filter."); var outcome = await subsequent(endpointFilterInvocationContext); return outcome; }) .AddEndpointFilter(async (endpointFilterInvocationContext, subsequent) => { app.Logger.LogInformation("That is the third Filter."); var outcome = await subsequent(endpointFilterInvocationContext); return outcome; });
Parameter binding in motion strategies utilizing DI
With ASP.NET Core 7, you possibly can make the most of dependency injection to bind parameters within the motion strategies of your API controllers. So, if the sort is configured as a service, you now not want so as to add the [FromServices] attribute to your technique parameters. The next code snippet illustrates this.
[Route("[controller]")] [ApiController] public class MyDemoController : ControllerBase { public ActionResult Get(IDateTime dateTime) => Okay(dateTime.Now); }
Typed leads to minimal APIs
The IResult interface was added in .NET 6 to signify values returned from minimal APIs that don’t make use of the implicit help for JSON serializing the returned object. It needs to be famous right here that the static End result class is used to create varied IResult objects that signify various kinds of responses, comparable to setting a return standing code or rerouting the consumer to a brand new URL. Nevertheless, as a result of the framework varieties returned from these strategies had been personal, it wasn’t doable to confirm the right IResult kind being returned from motion strategies throughout unit testing.
With .NET 7, the framework varieties that implement the IResult interface are actually public. Thus we are able to use kind assertions when writing our unit assessments, as proven within the code snippet given under.
[TestClass()] public class MyDemoApiTests { [TestMethod()] public void MapMyDemoApiTest() { var outcome = _MyDemoApi.GetAllData(); Assert.IsInstanceOfType(outcome, typeof(Okay<MyDemoModel[]>)); } }
You can even use IResult implementation varieties to unit check your route handlers in minimal APIs. The next code snippet illustrates this.
var outcome = (Okay<MyModel>)await _MyDemoApi.GetAllData()
Route teams in minimal APIs
With ASP.NET Core 7, you possibly can leverage the brand new MapGroup extension technique to arrange teams of endpoints that share a standard prefix in your minimal APIs. The MapGroup extension technique not solely reduces repetitive code, but in addition makes it simpler to customise total teams of endpoints.
The next code snippet exhibits how MapGroup can be utilized.
app.MapGroup("/public/authors") .MapAuthorsApi() .WithTags("Public");
The following code snippet illustrates the MapAuthorsApi extension technique.
public static class MyRouteBuilder { public static RouteGroupBuilder MapAuthorsApi(this RouteGroupBuilder group) { group.MapGet("https://www.infoworld.com/", GetAllAuthors); group.MapGet("/{id}", GetAuthor); group.MapPost("https://www.infoworld.com/", CreateAuthor); group.MapPut("/{id}", UpdateAuthor); group.MapDelete("/{id}", DeleteAuthor); return group; } }
Well being checks for gRPC
ASP.NET Core helps using the .NET Well being Checks middleware to report the well being of your software infrastructure parts. ASP.NET Core 7 provides built-in help for monitoring the well being of gRPC providers by means of the Grpc.AspNetCore.HealthChecks NuGet bundle. You should use this bundle to reveal an endpoint in your gRPC app that allows well being checks.
Observe that you’d sometimes use well being checks with an exterior monitoring system, or with a load balancer or container orchestrator. The latter may automate an motion comparable to restarting or rerouting across the service based mostly on well being standing. You’ll be able to learn extra about ASP.NET Core well being checks right here.
File uploads in minimal APIs
Now you can use IFormFile and IFormFileCollection in minimal APIs to add information in ASP.NET Core 7. The next code snippet illustrates how IFormFile can be utilized.
var builder = WebApplication.CreateBuilder(args); var app = builder.Construct(); app.MapPost("/uploadfile", async (IFormFile iformFile) => { var tempFileName = Path.GetTempFileName(); utilizing var fileStream = File.OpenWrite(tempFileName); await iformFile.CopyToAsync(fileStream); }); app.Run();
If you wish to add a number of information, you should utilize the next piece of code as a substitute.
var builder = WebApplication.CreateBuilder(args); var app = builder.Construct(); app.MapPost("/uploadfiles", async (IFormFileCollection information) => { foreach (var file in information) { var tempFileName = Path.GetTempFileName(); utilizing var fileStream = File.OpenWrite(tempFileName); await file.CopyToAsync(fileStream); } }); app.Run();
From output caching, rate-limiting, and request decompression middleware to filters, route maps, and different new capabilities for minimal APIs, ASP.NET Core 7 provides builders many new options that can make it a lot simpler and sooner to create sturdy internet functions. ASP.NET Core 7 permits sooner improvement utilizing modular parts, gives higher efficiency and scalability throughout a number of platforms, and simplifies deployment to internet hosts, Docker, Azure, and different internet hosting environments with built-in tooling.
On this article we’ve mentioned solely among the necessary new options in ASP.NET Core 7—my prime picks. You will discover the entire checklist of recent options in ASP.NET Core 7 right here.
Copyright © 2023 IDG Communications, Inc.