I have a web api in asp.net core 2.0. I have functionality that every request will pass the APIKey in header and my api server will read that apikey check it and allow the request if apikey is valid. I implemented it by using middleware.
Now this middleware executing before every request of whole api server. When request is coming for registration or login, API key will not there and server should allow them request without executing middleware...
- app.UseMiddleware
();
- if (context.Request.Path.Value.Contains("/user/authenticate") || context.Request.Path.Value.Contains("/user/register"))
- {
- await _next.Invoke(context); // call next middleware
- }


Sagar Pandurang KapRank #606 · 4K reputationPosted Mar 29, 2018, 1:11 AM EDT
Jignesh TrivediRank #16 · 50.3K reputationPosted May 27, 2018, 6:34 PM EDT
Dharmraj ThakurRank #577 · 4.2K reputationPosted May 27, 2018, 7:35 PM EDT
Dharmraj ThakurRank #577 · 4.2K reputationPosted Mar 29, 2018, 2:03 AM EDT
adhar jain90 reputationPosted Jan 30, 2023, 11:16 PM EST
Probably you are looking for below with some regex
app.UseWhen(context=>!context.Request.Path.Value.ToLower().Trim().Contains(@"/route"), applicationBuilder =>();
{
applicationBuilder.UseMiddleware
});
Naimish MakwanaRank #324 · 7.7K reputationPosted Jan 30, 2023, 11:36 PM EST
Hi,
Please refer below link. It may be helpful to you.
https://www.devtrends.co.uk/blog/conditional-middleware-based-on-request-in-asp.net-core
Thanks
Naimish
Sudhesh Gnanasekaran36 reputationPosted Mar 24, 2024, 10:57 AM EDT
Check out this article on how to ignore routes conditionally
https://codetrojan.com/csharp/asp-net-core-how-to-restrict-specific-routes-from-middleware/
Tuhin PaulRank #7 · 71.9K reputationPosted Mar 25, 2024, 7:10 AM EDT
private readonly string[] _allowedPaths = new string[] { "/user/authenticate", "/user/register" };Create a string array or list to store the paths for unrestricted access (login and registration)
Tuhin PaulRank #7 · 71.9K reputationPosted Mar 25, 2024, 7:11 AM EDT
Modify your
VerifyClientMiddlewareto check the request path before performing the API key validationpublic class VerifyClientMiddleware { private readonly RequestDelegate _next; public VerifyClientMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { // Check if current path is allowed without API key if (!_allowedPaths.Contains(context.Request.Path.Value)) { // Perform your existing API key validation logic here (read and check API key) // If key is invalid, throw an exception or return appropriate error response } // Call the next middleware in the pipeline await _next(context); } }