Date:

Share:

2 ways to define ASP.NET Core custom Middleware | Code4IT

Related Articles

Sometimes you need to create custom logic to be applied to all HTTP requests received by your ASP.NET Core application. In these cases, you can create a personalization middleware: Bits of code that are executed sequentially for all incoming requests.

The order of the middle matters. Here’s a nice schematic posted on Microsoft website:

Middleware, in fact, can manipulate the incoming HttpRequest and the received HttpResponse stuff.

In this article, we will learn 2 ways to create middleware in .NET.

middleware as embedded delegates

The easiest way is to define a representative role It must be defined after the The construction of the WebApplication.

by calling Use Method, you can update the HttpContext The object is passed as the first parameter.

app.Use(async (HttpContext context, Func<Task> task) =>
{
    context.Response.Headers.TryAdd("custom-header", "a-value");

    await task.Invoke();
});

Note that you need to call Invoke A method to call the next broker.

There is a similar overload that you get at input A RequestDelegate show on site Func<Task>But this is considered less performant: you should, in fact, use it with Func<Task>.

middleware as independent classes

The alternative to delegates is by defining a custom class.

You can call it whatever you want, but you have some constraints to follow after creating the class:

  • It must have a public constructor with a single parameter whose type is RequestDelegate (which will be used to activate the following middleware);
  • It must expose a public method named Invoke or InvokeAsync which accepts as a first parameter an HttpContext and returns a Task;

Here is an example:

public class MyCustomMiddleware
{
    private readonly RequestDelegate _next;

    public MyCustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        context.Response.Headers.TryAdd("custom-name", "custom-value");
        await _next(context);
    }
}

Then, to add it to your app, you need to call

app.UseMiddleware<MyCustomMiddleware>();

Lessons or personalized lessons?

Both are valid methods, but each performs well in specific cases.

For simple scenarios, go with embedded delegates: They are easy to set up, easy to read and quite performant. But they are a little Difficult to test.

For complex scenarios, go with custom classes: This way you can define complex behaviors in a single class, organize your code better, Use Dependency Injection to push services and configurations to the broker. Also, defining the middleware as a class makes it so more testable. The downside is that as of .NET 7, Using reflection-based middleware: UseMiddleware Invokes the middleman by searching for a public method named Invoke or InvokeAsync. So, in theory, using classes is less performant than using delegates (though I haven’t tested this yet!).

finishing

In the Microsoft documentation you can find a well-explained introduction to middlewares:

🔗 ASP.NET Core Middleware | Microsoft docs

And some suggestions on how to write custom middleware as independent classes:

🔗 Write custom ASP.NET Core software | Microsoft docs

I hope you enjoyed this article! Let’s keep in touch Twitter or LinkedIn! 🤜🤛

Happy coding!

🐧

[ ] Nome cartella e slug devono combaciare
[ ] Imagine Di Cupertina
[ ] Police format

.

Source

Popular Articles