SHARE:

ASP.NET Core 7: Introducing endpoint filters, actions filters for minimal APIs

Introduction

You have been waiting for that feature for a while right ? ASP.NET Core 7 made it! It’s now possible to enjoy the same kind of action filters we used to design on ASP.NET Core MVC and ASP.NET Core Web APIs applications. in this article I will show you how to design them and how to use them

Basic filters

ASP.NET Core 7 introduces a new extension method named AddEndpointFilter that allows you to define any operation before and after the minimal endpoint is executed, exactly like Action filters. The usage of the AddEndpointFilter extension looks like the ASP.NET Core middlewares which takes in parameter a delegate which has itself two parameters, the first one a EndpointFilterInvocationContext object, in others words the current HttpContext and a delegate EndpointFilterDelegate which correspond to the next chained element (let’s say middleware) to get executed in the ASP.NET Core pipeline. The following example shows a GET endpoint which takes in its route a firstname and display it in the response with a “Hello” message. Note that, Injection dependency, in this basic filter, requires to access GetRequiredService method from HttpContext.RequestServices object to get an instance of a service. We will see later how to access services in the DI more elegantly.

This code gives the following output:

Pretty simple right? Now let’s see a more customizable endpoint filter

Custom filters

ASP.NET Core 7 allows you to write custom endpoint filters. What you have to do is to write a class that implements the IEndpointFilter interface and write your custom async ValueTask InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) method as follow:

As you can see it’s more elegant to design to filter into a separate class, you can even using injection dependency by constructor! To use it, apply it on your endpoint as follow:

That’s it 🙂

If you want more example about these filters, please notify me I will provide you more samples !

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: