Conditional pipeline

ASP.NET Core provides some useful operators that let us put conditional initialization logic inside the middleware pipeline. Those kinds of operators may assist in providing additional performance benefits to our services and applications. Let's have a look at some of these operators.

The IApplicationBuilder Map (this IApplicationBuilder app, PathString pathMatch, Action<IApplicationBuilder> configuration) extension method helps us to initialize our middleware by mapping a URI path; for example:

public static class SampleMiddlewareExtensions
{
public static IApplicationBuilder UseSampleMiddleware(
this IApplicationBuilder builder)
{
return builder.Map("/test/path", _ =>
_.UseMiddleware<SampleMiddleware>());
}
}

In this case, SampleMiddleware will only be added to our pipeline if it is called as a URI with the specified path. Notice that the Map operator can also be nested inside others: this approach provides a more advanced approach to conditional initialization.

Another useful operator is MapWhen, which only initializes the middleware provided as a parameter if the predicate function returns true; for example:

public static class SampleMiddlewareExtensions
{
public static IApplicationBuilder UseSampleMiddleware(
this IApplicationBuilder builder)
{
return builder.MapWhen(context => context.Request.IsHttps,
_ => _.UseMiddleware<SampleMiddleware>());
}
}

In this case, if the request is HTTPS, we will initialize the SampleMiddleware class. Conditional middleware initialization can be really useful when we need to act on a specific type of request. It usually becomes necessary when we need to force the execution of some logic on HTTP request types, such as when a specific header is present in the request, or a specific protocol is used.

In conclusion, class-based middleware is really useful when we need to implement custom logic in the middleware pipeline, and conditional initialization provides a cleaner way to initialize our set of middleware. In ASP.NET Core, middleware is a first-class citizen of the base logic of the framework; therefore, the next section covers some use cases and some middleware that comes out of the box with ASP.NET Core.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.23.130