.NET Core 5中间件InvokeAsync未触发

dav*_*vid 0 middleware asp.net-core .net-5

我有一个使用 .NET Core 2.2 中间件的后端解决方案,并将其更新到 .NET Core 5,但InvokeAsync不再触发该方法。

\n

这是我的代码:

\n

启动(在configureservices中):

\n
app.UseMiddleware<ValidRouteMiddleware>();\napp.UseMiddleware<ValidNuisAlgoTokenAndAdminMiddleware>();\napp.UseMiddleware<CheckIdChantierDefaultMiddleware>();\napp.UseMiddleware<ValidationCatcherMiddleware>();\n
Run Code Online (Sandbox Code Playgroud)\n

有效路由中间件:

\n
public class ValidRouteMiddleware\n{\n    private readonly ILogger<ValidRouteMiddleware> _logger;\n    private const string BadRouteErrorMessage = "Hello World d~.~b";\n    private readonly RequestDelegate _next;\n    private readonly List<string> _allRoutes;\n\n    public ValidRouteMiddleware(RequestDelegate next, ILogger<ValidRouteMiddleware> logger,\n       IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)\n    {\n        _next = next;\n        _logger = logger;\n        ....\n    }\n\n    public async Task InvokeAsync(HttpContext context)\n    {\n        if (!MiddlewareTools.CheckRoute(context,_allRoutes))\n        {\n            _...\n            return;\n        }\n        else\n        {\n            await _next.Invoke(context);\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

CheckIdChantierDefaultMiddleware:

\n
    public class CheckIdChantierDefaultMiddleware\n    {\n        private readonly ILogger<CheckIdChantierDefaultMiddleware> _logger;\n        private const string UnauthorizedErrorMessage = "Non autoris\xc3\xa9";\n        private readonly RequestDelegate _next;\n        private readonly List<string> _excludedRoutes;\n\n        public CheckIdChantierDefaultMiddleware(RequestDelegate next, ILogger<CheckIdChantierDefaultMiddleware> logger,\n            IActionDescriptorCollectionProvider actionDescriptorCollectionProvider)\n        {\n            _next = next;\n            ...\n        }\n\n        public async Task InvokeAsync(HttpContext context, ComInDbContext dbContext)\n        {\n        }\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

ETC...

\n

缺什么 ?

\n

问候

\n

注意:整个Startup/ConfigureServices

\n
public void Configure(IApplicationBuilder app, IHostApplicationLifetime appLifetime, IWebHostEnvironment env, ILogger<Startup> logger)\n{\n    Logger = logger;\n    Logger.LogInformation($"Environnement d'ex\xc3\xa9cution : {Environment.EnvironmentName}");\n\n    appLifetime.ApplicationStarted.Register(OnApplicationStarted);\n    appLifetime.ApplicationStopping.Register(OnApplicationStopping);\n    appLifetime.ApplicationStopped.Register(OnApplicationStopped);\n\n    if (env.IsDevelopment())\n    {\n        app.UseDeveloperExceptionPage();\n    }\n    else\n    {\n        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.\n        app.UseHsts();\n    }\n\n    // Pour la g\xc3\xa9n\xc3\xa9ration des PDFs, on doit injecter la lib en 32 ou 64\n    var wkHtmlToPdfContext = new CustomAssemblyLoadContext();\n    var architectureFolder = (IntPtr.Size == 8) ? "64 bits" : "32 bits";\n    // Folder dans Infrastructure.PDF\n    var wkHtmlToPdfPath = Path.Combine(AppContext.BaseDirectory, $"libwkhtmltox\\\\{architectureFolder}\\\\libwkhtmltox");\n    wkHtmlToPdfContext.LoadUnmanagedLibrary(wkHtmlToPdfPath);\n\n    app.UseRouting();\n\n    // Utilisation de la r\xc3\xa8gle du CORS\n    Logger.LogInformation($"Application de la r\xc3\xa8gle `{filteredOrigin}` pour le CORS");\n    app.UseCors(filteredOrigin);\n\n    // Swagger uniquement en DEV\n    if (Environment.EnvironmentName == "Development" || Environment.EnvironmentName == "PreProduction")\n    {\n        // Active Swagger\n        Logger.LogInformation($"Activation de Swagger (sur l'URL \\"/swagger\\") ...");\n        app.UseSwagger();\n        app.UseSwaggerUI(c =>\n        {\n            c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger - Administration API");\n            c.RoutePrefix = String.Empty;\n        });\n    }\n\n    // Active les signaux de HealthCheck sur l'url de routage "/health"\n    Logger.LogInformation($"Activation des HealthCheck (sur l'URL \\"/health\\") ...");\n    // Active le pipeline d'Endpoints\n    Logger.LogInformation($"Activation du pipeline d'Endpoints ...");\n    app.UseEndpoints(endpoints =>\n    {\n        endpoints.MapControllers();\n        endpoints.MapHealthChecks("/health",\n            new HealthCheckOptions\n            {\n                ResponseWriter = async (context, report) =>\n                {\n                    var result = JsonSerializer.Serialize(\n                        new\n                        {\n                            status = report.Status.ToString(),\n                            errors = report.Entries.Select(e => new { key = e.Key, value = Enum.GetName(typeof(HealthStatus), e.Value.Status) })\n                        });\n                    context.Response.ContentType = MediaTypeNames.Application.Json;\n                    await context.Response.WriteAsync(result, context.RequestAborted);\n                }\n            });\n    });\n\n    app.UseHttpsRedirection();\n\n    #region Middleware\n\n    // Active le middleware pour la v\xc3\xa9rification des headers\n    app.UseMiddleware<ValidRouteMiddleware>();\n    app.UseMiddleware<ValidNuisAlgoTokenAndAdminMiddleware>();\n    app.UseMiddleware<CheckIdChantierDefaultMiddleware>();\n    app.UseMiddleware<ValidationCatcherMiddleware>();\n\n    #endregion Middleware\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Xin*_*hen 5

我这里写了一个简单的demo。endpoint首先我创建一个自定义中间件并在之前的Configure方法中注册它startup,然后你可以看到 InvokeAsync 成功触发

在此输入图像描述

当我注册中间件后endpoint,InvokeAsync将不会被触发。

在此输入图像描述

Panagiotis Kanavos 已经解释了,Endpoint或者您可以阅读有关 Asp .net core 5 中的路由的内容

  • 发布代码,而不是图像或更糟糕的是,在完成之前无法阅读的闪烁动画。浏览器无法暂停 GIF 动画。有人需要图像处理软件来检查帧并理解您发布的内容。图像也无法复制或编译 (2认同)