How you can work with endpoint filters in ASP.NET Core 7

Deal Score0
Deal Score0


With ASP.NET Core 7, we will reap the benefits of the newly launched IEndpointFilter interface to create filters and fix them to the endpoints in our minimal APIs. These filters can be utilized to change request or response objects or to short-circuit the request processing pipeline.

This text discusses how we will work with endpoint filters when constructing minimal API purposes in ASP.NET Core 7. To make use of the code examples supplied on this article, you need to have Visible Studio 2022 put in in your system. If you happen to don’t have already got a replica, you’ll be able to download Visual Studio 2022 here.

Create an ASP.NET Core 7 minimal Net API undertaking in Visible Studio 2022

First off, let’s create an ASP.NET Core 7 undertaking in Visible Studio 2022 Preview. Observe these steps:

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new undertaking.”
  3. Within the “Create new undertaking” window, choose “ASP.NET Core Net API” from the checklist of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new undertaking” window, specify the identify and site for the brand new undertaking.
  6. Optionally verify the “Place answer and undertaking in the identical listing” verify field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Further Data” window proven subsequent, choose “NET 7.0 (Present)” because the framework and uncheck the verify field that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Depart “Authentication Sort” set to “None” (default).
  9. Be certain that the verify bins “Allow OpenAPI Help,” “Allow Docker”, “Configure for HTTPS,” and “Allow Open API Help” are unchecked as we received’t be utilizing any of these options right here.
  10. Click on Create.

We’ll use this ASP.NET Core 7 Net API undertaking to create a minimal API and implement endpoint filters within the sections under.

What’s an endpoint filter?

A filter is code that may be run at totally different factors throughout the request processing pipeline, earlier than or after an motion. You possibly can use a filter to verify for authorization, or to verify request parameters, or to document every time an online web page is accessed, for instance.

An endpoint filter may be invoked on actions and on route endpoints. An endpoint is a URL that’s the entry level for an software, corresponding to http://instance.com/.

Key advantages of filters embody enhanced safety and simplify your code base by means of code reuse. For instance, you need to use filters to:

  • Reject requests that don’t meet particular standards.
  • Create reusable features and courses.
  • Give attention to the enterprise logic of your software as a substitute of spending time writing code for cross-cutting issues.
  • Execute code earlier than and after an endpoint handler.
  • Log request and response metadata.
  • Validate a request and request parameters.

An endpoint filter lets you intercept an incoming request, alter it, short-circuit it, and even consolidate your cross-cutting issues in a single place. Typical examples of cross-cutting issues that might be dealt with in a single class are authorization, validation, and exception dealing with.

The IEndpointFilter interface in ASP.NET Core 7

ASP.NET Core 7 introduces a brand new interface named IEndpointFilter that can be utilized to change the request, modify the response, or short-circuit the request pipeline. The IEndpointFilter interface can be utilized so as to add data to incoming requests earlier than the endpoint processes them.

The IEndpointFilter interface is outlined within the Microsoft.AspNetCore.Http namespace as proven under.

 
public interface IEndpointFilter
{
    ValueTask<object?> InvokeAsync(
        EndpointFilterInvocationContext context,
        EndpointFilterDelegate subsequent);
}

Why ought to I take advantage of the IEndpointFilter interface?

The IEndpointFilter interface is used so as to add performance to an HTTP endpoint. It’s a easy interface with just one methodology, referred to as InvokeAsync, that may add customized logic to the request/response pipeline.

You should utilize the IEndpointFilter interface while you need to modify the request or response at a selected level within the pipeline. You should utilize it to place your whole cross-cutting parts, corresponding to logging, authentication, authorization, and encryption, in a single place, the place you’ll be able to preserve them with out altering some other a part of your software’s code that leverages these parts.

Create an endpoint filter in ASP.NET Core 7

You possibly can register a filter by utilizing a delegate that accepts EndPointFilterInvocationContext as a parameter and returns an EndpointFilterDelegate. The EndPointFilterInvocationContext occasion offers entry to the HttpContext of the present request.

The next code snippet exhibits how one can create a easy endpoint filter that returns some textual content. Word how HttpContext has been used to retrieve the Request headers.

 
string AuthorName(string writer) => $"Identify of writer: {writer}";
app.MapGet("/endpointfilterexample/{writer}", AuthorName)
    .AddEndpointFilter(async (invocationContext, subsequent) =>
    {
        var httpContext = invocationContext.HttpContext;
        var requestHeaders = httpContext.Request.Headers;
        var writer = invocationContext.GetArgument<string>(0);
        return await subsequent(invocationContext);
    });

Once you execute the preceeding piece of code, the request headers shall be displayed as proven in Determine 1 under.

aspnet core endpoint filters IDG

Determine 1. ASP.NET Core 7 endpoint filters in motion.

Chain a number of endpoint filters collectively in ASP.NET Core 7

The next code demonstrates how a number of endpoint filters may be chained collectively within the default endpoint.

 
app.MapGet("https://www.infoworld.com/", () =>
{
    return "Demonstrating a number of filters chained collectively.";
})
.AddEndpointFilter(async (endpointFilterInvocationContext, subsequent) =>
    {
        app.Logger.LogInformation("That is the primary filter.");
        var consequence = await subsequent(endpointFilterInvocationContext);
        return consequence;
    })
.AddEndpointFilter(async (endpointFilterInvocationContext, subsequent) =>
    {
        app.Logger.LogInformation("That is the second filter.");
        var consequence = await subsequent(endpointFilterInvocationContext);
        return consequence;
    })
.AddEndpointFilter(async (endpointFilterInvocationContext, subsequent) =>
    {
        app.Logger.LogInformation("That is the third context.");
        var consequence = await subsequent(endpointFilterInvocationContext);
        return consequence;
    });

Once you execute the endpoint, the three endpoint filters shall be executed one after one other.

Create a customized filter in a minimal API in ASP.NET Core 7

You can even create customized filters by implementing the IEndpointFilter interface as proven within the code snippet given under.

 
public class MyCustomFilter : IEndpointFilter
{
    public async ValueTask<object?> InvokeAsync(
        EndpointFilterInvocationContext context,
        EndpointFilterDelegate subsequent
    )
    {
        if (context.HttpContext.GetRouteValue("metropolis") is string metropolis)
        {
            return Outcomes.Okay($"The identify of the town is: {metropolis}");
        }
        return await subsequent(context);
    }
}
app.MapGet("/demo/{metropolis}", () =>
{
    return "Execute filters in a series.";
})
.AddEndpointFilter<MyCustomFilter>();

To entry the parameters related to a specific HTTP request, you need to use the GetArguments methodology of the EndpointFilterInvocationContext object. In case you have a number of filters, you’ll be able to register them utilizing the next code in your Program.cs file.

 
app.MapGet("https://www.infoworld.com/", () =>
{
    return "It is a pattern textual content.";
})
.AddEndpointFilter<MyCustomFilterA>()
.AddEndpointFilter<MyCustomFilterB>()
.AddEndpointFilter<MyCustomFilterC>();

Filters in ASP.NET Core let you run customized code earlier than or after a sure level within the request processing pipeline. You possibly can reap the benefits of endpoint filters to short-circuit endpoint executions or implement validation logic in your minimal API. I’ll talk about endpoint filters in additional element in a future put up right here.

Copyright © 2022 IDG Communications, Inc.

We will be happy to hear your thoughts

Leave a reply

informatify.net
Logo
Enable registration in settings - general