I had a backend solution using a middleware with .NET Core 2.2 and I updated this to .NET Core 5, but the InvokeAsync method is no longer triggered.
This is my code:
Startup (in configureservices):
app.UseMiddleware<ValidRouteMiddleware>();
app.UseMiddleware<ValidNuisAlgoTokenAndAdminMiddleware>();
app.UseMiddleware<CheckIdChantierDefaultMiddleware>();
app.UseMiddleware<ValidationCatcherMiddleware>();
ValidRouteMiddleware:
public class ValidRouteMiddleware
{
private readonly ILogger<ValidRouteMiddleware> _logger;
private const string BadRouteErrorMessage = "Hello World d~.~b";
private readonly RequestDelegate _next;
private readonly List<string> _allRoutes;
public ValidRouteMiddleware(RequestDelegate next, ILogger<ValidRouteMiddleware> logger,
IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
{
_next = next;
_logger = logger;
....
}
public async Task InvokeAsync(HttpContext context)
{
if (!MiddlewareTools.CheckRoute(context,_allRoutes))
{
_...
return;
}
else
{
await _next.Invoke(context);
}
}
}
CheckIdChantierDefaultMiddleware:
public class CheckIdChantierDefaultMiddleware
{
private readonly ILogger<CheckIdChantierDefaultMiddleware> _logger;
private const string UnauthorizedErrorMessage = "Non autorisé";
private readonly RequestDelegate _next;
private readonly List<string> _excludedRoutes;
public CheckIdChantierDefaultMiddleware(RequestDelegate next, ILogger<CheckIdChantierDefaultMiddleware> logger,
IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)
{
_next = next;
...
}
public async Task InvokeAsync(HttpContext context, ComInDbContext dbContext)
{
}
}
etc...
What is missing ?
Regards
Note: The entire Startup/ConfigureServices
public void Configure(IApplicationBuilder app, IHostApplicationLifetime appLifetime, IWebHostEnvironment env, ILogger<Startup> logger)
{
Logger = logger;
Logger.LogInformation($"Environnement d'exécution : {Environment.EnvironmentName}");
appLifetime.ApplicationStarted.Register(OnApplicationStarted);
appLifetime.ApplicationStopping.Register(OnApplicationStopping);
appLifetime.ApplicationStopped.Register(OnApplicationStopped);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
// Pour la génération des PDFs, on doit injecter la lib en 32 ou 64
var wkHtmlToPdfContext = new CustomAssemblyLoadContext();
var architectureFolder = (IntPtr.Size == 8) ? "64 bits" : "32 bits";
// Folder dans Infrastructure.PDF
var wkHtmlToPdfPath = Path.Combine(AppContext.BaseDirectory, $"libwkhtmltox\\{architectureFolder}\\libwkhtmltox");
wkHtmlToPdfContext.LoadUnmanagedLibrary(wkHtmlToPdfPath);
app.UseRouting();
// Utilisation de la règle du CORS
Logger.LogInformation($"Application de la règle `{filteredOrigin}` pour le CORS");
app.UseCors(filteredOrigin);
// Swagger uniquement en DEV
if (Environment.EnvironmentName == "Development" || Environment.EnvironmentName == "PreProduction")
{
// Active Swagger
Logger.LogInformation($"Activation de Swagger (sur l'URL \"/swagger\") ...");
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger - Administration API");
c.RoutePrefix = String.Empty;
});
}
// Active les signaux de HealthCheck sur l'url de routage "/health"
Logger.LogInformation($"Activation des HealthCheck (sur l'URL \"/health\") ...");
// Active le pipeline d'Endpoints
Logger.LogInformation($"Activation du pipeline d'Endpoints ...");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health",
new HealthCheckOptions
{
ResponseWriter = async (context, report) =>
{
var result = JsonSerializer.Serialize(
new
{
status = report.Status.ToString(),
errors = report.Entries.Select(e => new { key = e.Key, value = Enum.GetName(typeof(HealthStatus), e.Value.Status) })
});
context.Response.ContentType = MediaTypeNames.Application.Json;
await context.Response.WriteAsync(result, context.RequestAborted);
}
});
});
app.UseHttpsRedirection();
#region Middleware
// Active le middleware pour la vérification des headers
app.UseMiddleware<ValidRouteMiddleware>();
app.UseMiddleware<ValidNuisAlgoTokenAndAdminMiddleware>();
app.UseMiddleware<CheckIdChantierDefaultMiddleware>();
app.UseMiddleware<ValidationCatcherMiddleware>();
#endregion Middleware
}
CodePudding user response:
I doubt this code ever worked in .NET Core 2. Middleware blocks process requests in the order they're registered. Everything in ASP.NET Core is a middleware block, including HTTPS, authentication, CORS, controller support, routing, endpoints, with endpoints acting as the last step in the middleware chain.
Anything registered after the endpoints will never be called. That includes both the custom middleware and the HTTPS redirection step.
At the very least you need to place UseHttpsRedirection after the if (env.IsDevelopment()) block, and register your custom middleware before UseEndpoints.
I suggest creating a new ASP.NET Core MVC application and inspecting the code. The middleware is already in the correct order.
.NET Core LTS versions
You should also consider skipping .NET 5 and going straight to .NET 6. .NET 5 is a short term release which reaches 
When I register middleware after endpoint, InvokeAsync will not be triggered .
Panagiotis Kanavos has explained the Endpoint or you can read this about routing in Asp .net core 5


