Friday, December 16, 2022
HomeITHow one can work with endpoint filters in ASP.NET Core 7

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


With ASP.NET Core 7, we are able to benefit from the newly launched IEndpointFilter interface to create filters and fasten them to the endpoints in our minimal APIs. These filters can be utilized to switch request or response objects or to short-circuit the request processing pipeline.

This text discusses how we are able to 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 must have Visible Studio 2022 put in in your system. For those who don’t have already got a replica, you possibly can obtain Visible Studio 2022 right here.

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

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

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new venture.”
  3. Within the “Create new venture” window, choose “ASP.NET Core Net API” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new venture” window, specify the identify and site for the brand new venture.
  6. Optionally test the “Place resolution and venture in the identical listing” test field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Extra Data” window proven subsequent, choose “NET 7.0 (Present)” because the framework and uncheck the test field that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Go away “Authentication Kind” set to “None” (default).
  9. Be sure that the test containers “Allow OpenAPI Assist,” “Allow Docker”, “Configure for HTTPS,” and “Allow Open API Assist” 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 venture 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 in the course of the request processing pipeline, earlier than or after an motion. You could possibly use a filter to test for authorization, or to test request parameters, or to document every time an online web page is accessed, for instance.

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

Key advantages of filters embrace enhanced safety and simplify your code base via code reuse. For instance, you should use filters to:

  • Reject requests that don’t meet particular standards.
  • Create reusable features and lessons.
  • Concentrate on the enterprise logic of your utility as an alternative of spending time writing code for cross-cutting considerations.
  • 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 considerations in a single place. Typical examples of cross-cutting considerations that could possibly 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 switch the request, modify the response, or short-circuit the request pipeline. The IEndpointFilter interface can be utilized so as to add info 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 exploit 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 need to use the IEndpointFilter interface whenever you wish to modify the request or response at a selected level within the pipeline. You need to use it to place all your cross-cutting elements, corresponding to logging, authentication, authorization, and encryption, in a single place, the place you possibly can keep them with out altering another a part of your utility’s code that leverages these elements.

Create an endpoint filter in ASP.NET Core 7

You may 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) => $"Title 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);
    });

If you execute the preceeding piece of code, the request headers might 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 will 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 outcome = await subsequent(endpointFilterInvocationContext);
        return outcome;
    })
.AddEndpointFilter(async (endpointFilterInvocationContext, subsequent) =>
    {
        app.Logger.LogInformation("That is the second filter.");
        var outcome = await subsequent(endpointFilterInvocationContext);
        return outcome;
    })
.AddEndpointFilter(async (endpointFilterInvocationContext, subsequent) =>
    {
        app.Logger.LogInformation("That is the third context.");
        var outcome = await subsequent(endpointFilterInvocationContext);
        return outcome;
    });

If you execute the endpoint, the three endpoint filters might be executed one after one other.

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

You may also 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 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 selected HTTP request, you should use the GetArguments methodology of the EndpointFilterInvocationContext object. When you have a number of filters, you possibly can 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 will let you run customized code earlier than or after a sure level within the request processing pipeline. You may benefit from 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 submit right here.

Copyright © 2022 IDG Communications, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments