Dynamic Middleware Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Thu, 09 Nov 2023 06:05:19 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 Dynamic Middleware Archives - Tech Insights 32 32 230003556 Dynamic Middleware | Conditionally add middleware in ASP.NET Core https://reactconf.org/dynamic-middleware-conditionally-add-middleware-in-asp-net-core/ https://reactconf.org/dynamic-middleware-conditionally-add-middleware-in-asp-net-core/#respond Thu, 09 Nov 2023 06:05:19 +0000 https://labpys.com/?p=2083 This article explores configuring ASP.NET Core middleware Conditionally, in a way that allows you to have different middleware setups for different types of requests. For instance, in a project with …

The post Dynamic Middleware | Conditionally add middleware in ASP.NET Core appeared first on Tech Insights.

]]>
This article explores configuring ASP.NET Core middleware Conditionally, in a way that allows you to have different middleware setups for different types of requests. For instance, in a project with both MVC and Web API actions, you can implement distinct error-handling approaches for each request.

Create an Asp.NET Core MVC or Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project.

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web Application” from the list of available templates.
  • Click the Next button.
  • Then configure a new project, and specify the name and location of your project.
  • Click the “Next” button.
  • Then select .NET Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Create Middleware in Asp.Net Core

Visual Studio provides a template for creating standard middleware classes. To access this template, right-click on the project or folder where you want to create the middleware class and select Add>New Item, this will open the Add New Item dialog box. In the search bar located at the top right corner, type middleware to filter the available items. Select the middleware class item and provide a name for your class. Click the Add button to create the middleware class as shown below.

Conditionally add middleware in ASP.NET Core
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace middleware_App
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class MiddlewareException
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

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

        public async Task InvokeAsync(HttpContext httpContext)
        {
            
            await  _next.Invoke(httpContext);                     

        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class ErrorExceptionExtensions
    {
        public static IApplicationBuilder UseErrorException(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MiddlewareException>();
        }
    }
}

Registering middleware with Use*

Adding it to the “Program.cs” file requires only a single line:

app.UseMiddlewareMVC();

Conditionally middleware with UseWhen

In some cases, you may want to apply most of your middleware to all requests. But you have specific conditions for certain requests. This can be easily achieved with “UseWhen” method, which also uses a predicate to determine if the middleware should run

app.UseWhen(
    context => context.Request.Path.StartsWithSegments("/api"),
    builder => builder.UseMiddleware<MiddlewareException>()
    );

The UseWhen method takes two parameters. The first parameter is a delegate of type Func<T,bool>, which returns a Boolean value indicating whether the middleware should be executed. If the delegate returns true, the middleware will be applied to the request, otherwise, it will be skipped.

See Also

Encode and Decode URLs in ASP.NET Core C#

The post Dynamic Middleware | Conditionally add middleware in ASP.NET Core appeared first on Tech Insights.

]]>
https://reactconf.org/dynamic-middleware-conditionally-add-middleware-in-asp-net-core/feed/ 0 2083