
Note. For basic details, Please refer to the previous article, Unraveling Middleware Decoding
For Custom Middleware, Please refer to this article: Custom Middleware
What is Short-Circuiting?
Short-circuiting is a powerful technique that allows us to interrupt the usual flow of middleware execution, providing an early response under specific conditions. This can be instrumental in optimizing performance, implementing specialized handling, or even enforcing certain policies.
public class ShortCircuitValidateRequestPathMiddleware
{
private readonly RequestDelegate _next;
private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
private readonly List<string?> path ;
public ShortCircuitValidateRequestPathMiddleware(RequestDelegate next, IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
{
_next= next;
_actionDescriptorCollectionProvider= actionDescriptorCollectionProvider;
///
/// !!! For Example only, We need to lookup for better way.
///
path = [];
path = _actionDescriptorCollectionProvider.ActionDescriptors.Items.Where(
ad => ad.AttributeRouteInfo != null).Select(
ad => ad.AttributeRouteInfo?.Template).ToList();
Debug.WriteLine("ShortCircuitValidateRequestPathMiddleware CTOR Called .....");
}
public async Task Invoke(HttpContext context)
{
Debug.WriteLine("ShorCircuit ");
if (context.Request.Path.HasValue && path.Any(x => !string.IsNullOrWhiteSpace(x) &&
x.ToLower().Equals(context.Request.Path.Value.ToLower().Replace("/", ""))))
{
// Call the next middleware in the pipeline
await _next(context);
Debug.WriteLine($"\t Next Middleware Executed");
}
else {
Debug.WriteLine($"\t Bye pass for unknow call.");
}
}
}
In the provided code snippet, during the initialization of the application, we gather and compile a comprehensive list of all potential routes. These route paths are then stored in an array. Upon receiving each incoming request, the service undergoes a check to verify whether the requested path exists within the locally stored array of routes. If the path is present, the request is permitted to proceed; otherwise, the service rejects the request, terminating its processing.





Join the conversation! Your thoughts help the community grow.