.NET 5.0 API项目报InvalidOperationException,求解决中间件顺序问题
.NET 5.0 API 启动报错解决方案
报错信息
InvalidOperationException: EndpointRoutingMiddleware matches endpoints setup by EndpointMiddleware and so must be added to the request execution pipeline before EndpointMiddleware. Please add EndpointRoutingMiddleware by calling 'IApplicationBuilder.UseRouting'
问题原因
- 请求管道中缺失
UseRouting()中间件,它是端点路由的核心组件,必须在UseEndpoints()之前添加 - 中间件顺序错误:
UseAuthentication()必须在UseAuthorization()之前执行,否则授权逻辑无法获取合法的认证信息
修正后的Startup.cs核心代码
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAutoMapper(typeof(Startup)); var mapperConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); IMapper mapper = mapperConfig.CreateMapper(); services.AddSingleton(mapper); // 补充将mapper注册到DI容器,否则控制器无法注入使用 } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseExceptionHandler("/error"); // 新增路由中间件,必须置于UseEndpoints之前 app.UseRouting(); app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()); // 调整顺序:认证逻辑优先于授权逻辑执行 app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
额外说明
- 原代码中创建的
IMapper未注册到依赖注入容器,会导致控制器无法通过注入方式使用,补充services.AddSingleton(mapper)完成注册 - .NET请求管道对中间件顺序有严格要求,需遵循:异常处理 → 路由 → CORS → 认证 → 授权 → 端点映射的执行顺序
内容的提问来源于stack exchange,提问作者Anderson Constantino
相关产品推荐
相关产品推荐

