ASP.NET Core 6 launched a simplified internet hosting mannequin that permits us to construct light-weight APIs with minimal dependencies. Minimal APIs in ASP.NET Core 6 don’t use controllers, and so they lack help for a variety of helpful ASP.NET options. Considered one of these lacking options is filters.
Nonetheless, with ASP.NET Core 7 (now out there in a launch candidate), we are able to reap the benefits of the newly launched IRouteHandlerFilter interface to incoporate filters in our minimal APIs. These filters can be utilized to change the request or response objects as desired or to short-circuit the request processing pipeline.
This text discusses how we are able to work with route handler filters when constructing minimal API apps in ASP.NET Core 7. To make use of the code examples offered on this article, it is best to have Visible Studio 2022 Preview put in in your system. In the event you don’t have already got a duplicate, you may obtain Visible Studio 2022 right here.
Create an ASP.NET Core 7 minimal Net API challenge in Visible Studio 2022
First off, let’s create an ASP.NET Core 7 challenge in Visible Studio 2022 Preview. Comply with these steps:
- Launch the Visible Studio 2022 Preview IDE.
- Click on on “Create new challenge.”
- Within the “Create new challenge” window, choose “ASP.NET Core Net API” from the record of templates displayed.
- Click on Subsequent.
- Within the “Configure your new challenge” window, specify the identify and placement for the brand new challenge.
- Optionally examine the “Place answer and challenge in the identical listing” examine field, relying in your preferences.
- Click on Subsequent.
- Within the “Further Info” window proven subsequent, uncheck the examine field that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Go away the “Authentication Kind” as “None” (default).
- Be sure that the examine bins “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Assist” are unchecked as we received’t be utilizing any of these options right here.
- Click on Create.
We’ll use this ASP.NET Core 7 Net API challenge to create a minimal API and implement route handler filters within the sections under.
What are filters? Why ought to we use them?
Filters assist you to run code at sure levels of the request processing pipeline. In different phrases, a filter is a bit of code that’s executed earlier than or after an motion technique is executed. For instance, you may use a filter to log each time somebody accesses an online web page or to validate the request parameters despatched to an endpoint.
Filters provide a number of advantages:
- Filters make your software safer by permitting you to reject requests that don’t meet particular standards (together with authorization).
- Filters might help you clear up your code by creating reusable capabilities and lessons.
- Filters assist you to give attention to the enterprise logic of your software as a substitute of spending time writing code for cross-cutting considerations reminiscent of logging, exception dealing with, and safety.
Why ought to we use filters in minimal APIs?
You possibly can reap the benefits of filters in minimal APIs to jot down code that may do the next:
- Execute code earlier than and after an endpoint handler.
- Examine and edit the parameters when an endpoint handler executes.
- Examine the response habits of an endpoint handler.
- Log request and response metadata.
- Be sure that a request targets a supported API model.
- Validate a request and request parameters.
The IRouteHandlerFilter interface in ASP.NET Core 7
You possibly can reap the benefits of the IRouteHandlerFilter interface to change the request or response or to short-circuit the request processing pipeline. It’s also possible to add cross-cutting considerations reminiscent of authentication, authorization, and logging. At a fast look, right here’s what you may obtain utilizing this interface:
- Write customized logic for dealing with incoming requests.
- Intercept a request and modify the request object as required.
- Make modifications to the response earlier than it’s despatched out.
- Quick-circuit a request, that means that any remaining motion filters is not going to execute.
The next code snippet illustrates the IRoutehandler interface:
namespace Microsoft.AspNetCore.Http;
public interface IRouteHandlerFilter
{
ValueTask<object?> InvokeAsync(
RouteHandlerInvocationContext context,
RouteHandlerFilterDelegate subsequent);
}
Create a customized route handler filter in ASP.NET Core 7
You possibly can create a customized filter class through the IRouteHandlerFilter interface as proven within the code itemizing given under.
public class DemoFilter : IRouteHandlerFilter
{
non-public ILogger _logger;
public DemoFilter(ILoggerFactory loggerFactory)
{
_logger = logger;
}
public async ValueTask<object?> InvokeAsync(RouteHandlerInvocationContext context, RouteHandlerFilterDelegate subsequent)
{
var textual content = context.GetParameters[0];
if (textual content.Equals("Error"))
{
_logger.LogInformation(“Error.”);
return Outcomes.Drawback("This can be a minimal instance of an error.");
}
_logger.LogInformation(“Success.”);
return await subsequent(context);
}
}
Subsequent, it is best to register the filter as a service within the Program.cs file utilizing the next code snippet.
builder.Providers.AddSingleton<DemoFilter>();
It’s doable to register a filter by utilizing the RouteHandlerFilterDelegate or the AddFilter extension technique. On this instance, we’ll use the AddFilter extension technique. Write the next code snippet within the Program.cs file.
app.MapGet("/v1/MyDemoEndpoint{textual content}", “Hey”)
.AddFilter<DemoFilter>();
Create a brief circuit filter in ASP.NET Core 7
You would possibly typically have to short-circuit the request processing pipeline. For instance, let’s say you’ve constructed a microservices-based software and one of many companies isn’t responding. On this case, all requests to this service would fail. As a substitute, you may short-circuit the request processing pipeline and fall again on another service that’s wholesome.
Quick-circuiting is commonly the specified motion to keep away from pointless processing. For instance, if a request is generated for static information reminiscent of HTML, CSS, and JavaScript, you may write a filter that can intercept, deal with, and serve that request whereas short-circuiting the remainder of the pipeline. The short-circuiting stops the request processing pipeline and redirects the request to a fallback technique or service.
One other instance of brief circuiting is the circuit breaker sample in microservices-based purposes. This sample prevents an software from performing an operation that may fail. Sometimes, circuit breakers redirect requests to a fallback technique in case you encounter issues with a service or a service technique. So, when an outage arises due to a failed service, you need to use circuit breakers to redirect the request to fallback companies or strategies.
Right here is how one can implement a customized short-circuit filter in your minimal API:
public class MyShortCircuitFilter: IRouteHandlerFilter
{
public ValueTask<object?> InvokeAsync(
RouteHandlerInvocationContext context,
RouteHandlerFilterDelegate subsequent)
{
return new ValueTask<object?>(Outcomes.Json
(new { Message = "Terminated" }));
}
}
Filters assist you to run customized code earlier than or after a sure level within the request processing pipeline. Additionally they assist you keep away from the duplication of code throughout actions. The IRouteHandlerFilter Interface is a particular filter that may be utilized to a complete route or a single handler. It lets you entry the request object after which modify the request or response as required.
Copyright © 2022 IDG Communications, Inc.